Explicitly convert a lambda to function pointer

2019-08-09 00:07发布

问题:

I have a legacy template function I'm trying to call that has a slew of specializations for function pointers with different numbers of arguments. I'm writing a new template function of my own that take some arbitrary kind of non-capturing lambda and needs to pass it to the other library. If I do this directly, then the template resolution fails. If however I explicitly cast it to be related function pointer type, things work.

The problem then is how to make my template code get that function pointer type from the lambda's type or force the explicit conversion without explicitly referencing the type.

回答1:

Just use unary-plus to convert a lambda to a function pointer, as in:

 auto* f = +[]{ std::cout << "Hello, world!\n"; }; // f is of type void (*)()


标签: c++11 lambda