Home > Backend Development > C++ > Why Do Recursive Lambda Functions Fail with Auto Type Inference in C ?

Why Do Recursive Lambda Functions Fail with Auto Type Inference in C ?

Mary-Kate Olsen
Release: 2024-12-16 17:57:11
Original
238 people have browsed it

Why Do Recursive Lambda Functions Fail with Auto Type Inference in C  ?

Recursive Lambda Functions and Type Inference

Consider the following recursive lambda function:

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};
Copy after login

This code fails to compile with the following error:

error: ‘`((<lambda(int, int)>*)this)-><lambda(int, int)>::sum`’ cannot be used as a function
Copy after login

The issue stems from using auto to infer the type of the lambda function. When auto is used, the compiler attempts to infer the type from the initialization expression. However, in this case, the initialization expression itself needs to be aware of the type it's capturing, creating a circular dependency.

To resolve this, one can use a fully specified function object's type instead:

std::function<int(int,int)> sum = [term,next,&amp;sum](int a, int b)->int {
   if(a>b)
     return 0;
   else
     return term(a) + sum(next(a),b);
};
Copy after login

In this case, the compiler doesn't need to infer the type of the lambda closure, and the lambda can be fully informed about the types it's capturing.

Although recursive lambda functions can work with type inference, it's generally not advised as it can lead to compilation issues. Instead, specifying the type explicitly ensures that the compiler has all the necessary information at the time of compilation.

The above is the detailed content of Why Do Recursive Lambda Functions Fail with Auto Type Inference in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template