Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Lambda: Access static method in lambda leads to error 'this was not captured for this lambda function'

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_methodabove) 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?

like image 719
muffel Avatar asked Oct 20 '22 22:10

muffel


2 Answers

The following work-around works:

template< typename T > T* global_instance() { return T::instance(); }

void(*func_pointer)(void) = []{
    global_instance<Singleton>()->bar();
};
like image 89
Daniel Frey Avatar answered Oct 24 '22 10:10

Daniel Frey


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);
}
like image 40
6502 Avatar answered Oct 24 '22 10:10

6502