Consider the following code:
//this is what I want to call; I cannot modify its signature
void some_library_method(void(*fp)(void));
class Singleton{
public:
static Singleton *instance();
void foo();
void bar();
private:
Singleton();
};
void Singleton::foo(){
//this leads to an error ('this' was not captured for this lambda function)
void(*func_pointer)(void) = []{
Singleton::instance()->bar();
};
some_library_method(func_pointer);
}
I want to call a function I cannot modify (see some_library_method
above) which expects a function pointer as an argument. The call should be done in a class member foo()
. I do know that I cannot access class members there, but all I want to do is access the Class Singleton in a static way (retrieve the singleton instance).
Is there any way reform the lambda expression to show the target compiler, g++ v4.7.2, that it really does not need a reference to this
?
The following work-around works:
template< typename T > T* global_instance() { return T::instance(); }
void(*func_pointer)(void) = []{
global_instance<Singleton>()->bar();
};
You can use a locally defined regular function instead of a lambda for that
void Singleton::foo() {
struct T {
static void cb(){ Singleton::instance()->bar(); }
};
some_library_method(T::cb);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With