加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:06:53 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: //this is what I want to call; I cannot modify its signaturevoid some_library_method(void(*fp)(void));class Singleton{ public: static Singleton *instance(); void foo(); void bar(); private: Singleton();};void Singleton::fo
请考虑以下代码:
//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);
}

我想调用一个我无法修改的函数(参见some_library_methodabove),它希望函数指针作为参数.调用应该在类成员foo()中完成.我知道我无法访问那里的类成员,但我想要做的就是以静态方式访问Class Singleton(检索单例实例).

有没有办法改进lambda表达式来显示目标编译器g v4.7.2,它真的不需要引用它?

解决方法

以下解决方法:
template< typename T > T* global_instance() { return T::instance(); }

void(*func_pointer)(void) = []{
    global_instance<Singleton>()->bar();
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读