Recursive lambda functions in C++11

Think about the difference between the auto version and the fully specified type version. The auto keyword infers its type from whatever it’s initialized with, but what you’re initializing it with needs to know what its type is (in this case, the lambda closure needs to know the types it’s capturing). Something of a chicken-and-egg problem.

On the other hand, a fully specified function object’s type doesn’t need to “know” anything about what is being assigned to it, and so the lambda’s closure can likewise be fully informed about the types its capturing.

Consider this slight modification of your code and it may make more sense:

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);
};

Obviously, this wouldn’t work with auto. Recursive lambda functions work perfectly well (at least they do in MSVC, where I have experience with them), it’s just that they aren’t really compatible with type inference.

Leave a Comment