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); };
This code fails to compile with the following error:
error: ‘`((<lambda(int, int)>*)this)-><lambda(int, int)>::sum`’ cannot be used as a function
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,&sum](int a, int b)->int { if(a>b) return 0; else return term(a) + sum(next(a),b); };
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!