请考虑以下代码:
//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(); };