C++ lambdas 需要捕获“this”来调用静态成员函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4940259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
lambdas require capturing 'this' to call static member function?
提问by HighCommander4
For the following code:
对于以下代码:
struct B
{
void g()
{
[]() { B::f(); }();
}
static void f();
};
g++ 4.6 gives the error:
g++ 4.6 给出了错误:
test.cpp: In lambda function:
test.cpp:44:21: error: 'this' was not captured for this lambda function
test.cpp:在 lambda 函数中:
test.cpp:44:21:错误:此 lambda 函数未捕获“this”
(Interestingly, g++ 4.5 compiles the code fine).
(有趣的是,g++ 4.5 编译代码很好)。
Is this a bug in g++ 4.6, or is it really necessary to capture the 'this' parameter to be able to call a static member function? I don't see why it should be, I even qualified the call with B::
.
这是 g++ 4.6 中的错误,还是真的有必要捕获“this”参数才能调用静态成员函数?我不明白为什么会这样,我什至用B::
.
采纳答案by Mikael Persson
I agree, it should compile just fine. For the fix (if you didn't know already), just add the reference capture and it will compile fine on gcc 4.6
我同意,它应该编译得很好。对于修复(如果您还不知道),只需添加引用捕获,它就可以在 gcc 4.6 上正常编译
struct B
{
void g()
{
[&]() { B::f(); }();
}
static void f() { std::cout << "Hello World" << std::endl; };
};