简体   繁体   English

C ++ Lambda:lambda中的访问静态方法导致错误'这个lambda函数没有捕获这个'

[英]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_method above) which expects a function pointer as an argument. 我想调用一个我无法修改的函数(参见上面的some_library_method ),它希望函数指针作为参数。 The call should be done in a class member foo() . 调用应该在类成员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). 我知道我无法访问那里的类成员,但我想要做的就是以静态方式访问Class Singleton(检索单例实例)。

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 ? 有什么办法改革的lambda表达式显示目标的编译器,G ++ V4.7.2,它真的并不需要参考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 您可以使用本地定义的常规函数​​而不是lambda

void Singleton::foo() {
    struct T {
        static void cb(){ Singleton::instance()->bar(); }
    };
    some_library_method(T::cb);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM