I want to be able to obtain a function pointer to a lambda in C++.
I can do:
int (*c)(int) = [](int i) { return i; };
And, of course, the following works - even if it's not creating a function pointer.
auto a = [](int i) { return i; };
But the following:
auto *b = [](int i) { return i; };
Gives this error in GCC:
main.cpp: In function 'int main()':
main.cpp:13:37: error: unable to deduce 'auto*' from '<lambda closure object>main()::<lambda(int)>{}'
auto *b = [](int i) { return i; };
^
main.cpp:13:37: note: mismatched types 'auto*' and 'main()::<lambda(int)>'
It seems arbitrary that a lambda can be converted to a function pointer without issue, but the compiler cannot infer the function type and create a pointer to it using auto *
. Especially when it can implicitly convert a unique, lambda type
to a function pointer:
int (*g)(int) = a;
I've create a little test bed at http://coliru.stacked-crooked.com/a/2cbd62c8179dc61b that contains the above examples. This behavior is the same under C++11 and C++14.
question from:
https://stackoverflow.com/questions/37709874/obtaining-function-pointer-to-lambda 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…