C ++ Lambda:在lambda中访问静态方法会导致错误“此lambda函数未捕获此错误" [英] C++ Lambda: Access static method in lambda leads to error 'this was not captured for this lambda function'
问题描述
考虑以下代码:
//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()
中进行.我确实知道我不能在那里访问类成员,但是我要做的就是以静态方式访问类Singleton(检索Singleton实例).
I want to call a function I cannot modify (see some_library_method
above) 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).
是否可以通过某种方式重新构造lambda表达式以显示目标编译器g ++ v4.7.2,它确实不需要需要引用this
?
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
?
推荐答案
以下变通办法起作用:
template< typename T > T* global_instance() { return T::instance(); }
void(*func_pointer)(void) = []{
global_instance<Singleton>()->bar();
};
这篇关于C ++ Lambda:在lambda中访问静态方法会导致错误“此lambda函数未捕获此错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!