Home >Backend Development >C++ >Why Does a Recursive Lambda Function in C 0x Require Explicit Type Declaration?
In an attempt to create a recursive lambda, you encountered an error while using the auto keyword to infer the type of the lambda. However, when you explicitly declared the type of the lambda as a std::function, the code compiled successfully.
Auto Type Inference:
When using auto, the compiler infers the type of the lambda based on its initialization. However, for a recursive lambda, the lambda closure needs to know the types it's capturing (in this case, sum). This creates a circular dependency, as the lambda's type depends on the type of its closure, which in turn depends on the type of the lambda.
Explicit Type Declaration:
Declaring the type of the lambda as std::function
Recursive Function:
The revised code segment:
std::function<int(int, int)> sum; sum = [term, next, &sum](int a, int b) -> int { if (a > b) return 0; else return term(a) + sum(next(a), b); };
demonstrates that recursive lambda functions are perfectly viable in C 0x. They simply require explicit type declaration to overcome the type inference issue.
The above is the detailed content of Why Does a Recursive Lambda Function in C 0x Require Explicit Type Declaration?. For more information, please follow other related articles on the PHP Chinese website!