考虑以下代码:
//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_method),它需要一个函数指针作为参数。该调用应在类成员 foo() 中完成。我知道我不能在那里访问类成员,但我想做的就是以静态方式访问类单例(检索单例实例)。
有没有什么方法可以改革 lambda 表达式以向目标编译器 g++ v4.7.2 表明它确实不需要需要对 this 的引用?
最佳答案
以下解决方法:
template< typename T > T* global_instance() { return T::instance(); }
void(*func_pointer)(void) = []{
global_instance<Singleton>()->bar();
};
关于C++ lambda : Access static method in lambda leads to error 'this was not captured for this lambda function' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19514703/