Consider the following code:
#include <functional>
#include <iostream>
void normalFunction()
{
printf("bar");
}
int main()
{
std::function<void ()> f1 = []()
{
printf("foo123");
};
std::function<void()> f2 = normalFunction;
std::cout << f1.target<void (*)()>() << std::endl;
std::cout << f2.target<void (*)()>() << std::endl;
return 0;
}
The second line prints a valid address; the first call to target
, however, fails (nullptr
is returned), because the type of the stored callable is not void ()
, it's actually class <lambda_b356045a9ea53f6e7d502dd6abd8cae2>
(as target_type
tells us).
This means that std::function<T>::target
is very orthodox when checking the types and requires an exact match - even though the lambda can be converted to void (*)()
without any problem, since it is captureless.
Is there a way to overcome this behavior? I want to be able to pass callbacks to a function that interfaces with C code, so it needs to pass function pointers further. One option is to just have that function take a function pointer, since lambdas without capture can be converted implicitly; but out of curiosity, I wonder if there's a way to do this using std::function
.