no one special no one special - 2 months ago 8
C++ Question

lambda calling another external lambda

I can easily do this:

auto f = []()->int { return 4; };
auto g = [f]()->int { return f(); });
int i = g();


Nevertheless, I cannot do this:

int (*f)() = []()->int { return 4; };
int (*g)() = [f]()->int { return f(); });
int i = g();


Why I got such message in MSVC?

error C2440: 'initializing' : cannot convert from 'ClassName::functionName::< lambda_b2eebcdf2b88a20d8b40b0a03c412089>' to 'int (__cdecl *)(void)'


This occurs on line:

int (*g)() = [f]()->int { return f(); });


How to do this properly?

Answer
int (*f)() = []()->int { return 4; };

is still fine because lambdas with empty capture lists implicitly convert to matching function pointers.

This (crucial) condition is however not met in the second line:

int (*g)() = [f]()->int { return f(); });
              ^

Thus the conversion fails.

If you want to store a lambda that captures something, you either need an std::function, or deduce the type with auto as you did before; whatever fits your usecase. Function pointers simply cannot do that.

Comments