I’m starting to develop applications using C++11 lambdas, and need to convert some types to function pointers. This works perfectly in GCC 4.6.0:
void (* test)() = []()
{
puts("Test!");
};
test();
My problem is when I need to use function or method local variables within the lambda:
const char * text = "test!";
void (* test)() = [&]()
{
puts(text);
};
test();
G++ 4.6.0 gives the cast error code:
main.cpp: In function 'void init(int)':
main.cpp:10:2: error: cannot convert 'main(int argc, char ** argv)::<lambda()>' to 'void (*)()' in initialization
If use auto, it works ok:
const char * text = "Test!";
auto test = [&]()
{
puts(text);
};
test();
My question is: how can I create a type for a lambda with [&]? In my case, I can not use the STL std::function (because my program does not use C++ RTTI and EXCEPTIONS runtime), and It has a simple implementation of function to solve this problem?
Then you may need to write your own equivalent to
std::function.The usual implementation of type erasure for
std::functiondoesn’t need RTTI for most of its functionality; it works through regular virtual function calls. So writing your own version is doable.Indeed, the only things in
std::functionthat need RTTI are thetarget_typeandtargetfunctions, which are not the most useful functions in the world. You might be able to just usestd::functionwithout calling these functions, assuming that the implementation you’re using doesn’t need RTTI for its usual business.Typically, when you disable exception handling, the program simply shuts down and errors out when encountering a
throwstatement. And since most of the exceptions that astd::functionwould emit aren’t the kind of thing you would be able to recover from (calling an emptyfunction, running out of memory, etc), you can probably just usestd::functionas is.