C++ 除非它在捕获列表中,否则不能在 lambda 主体中引用封闭函数局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26903602/
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
an enclosing-function local variable cannot be referenced in a lambda body unless if it is in capture list
提问by user2957741
I have json::value object and I try to get values in a struct but i get this error about capture list. I understand that in then phrase this bracet [] holds capture list but i cant figure out how. How can i return a value in lambda function?
我有 json::value 对象,我尝试在结构中获取值,但我收到关于捕获列表的错误。我知道在那个短语中,这个括号 [] 包含捕获列表,但我无法弄清楚如何。如何在 lambda 函数中返回一个值?
void JsonDeneme::setValues(json::value obj)
{
weather.coord.lon = obj.at(L"coord").at(L"lon").as_double();
weather.coord.lat= obj.at(L"coord").at(L"lat").as_double();
}
void JsonDeneme::getHttp()
{
//json::value val;
http_client client(U("http://api.openweathermap.org/data/2.5/weather?q=Ankara,TR"));
client.request(methods::GET)
.then([](http_response response) -> pplx::task<json::value>
{
if (response.status_code() == status_codes::OK)
{
printf("Received response status code:%u\n", response.status_code());
return response.extract_json();
}
return pplx::task_from_result(json::value());
})
.then([ ](pplx::task<json::value> previousTask)
{
try
{
json::value v = previousTask.get();
setValues(v);//-----------------------------------------
}
catch (http_exception const & e)
{
wcout << e.what() << endl;
}
})
.wait();
}
回答by SingerOfTheFall
The capture-list is what you put inbetween the square brackets. Look at this example:
捕获列表是您放在方括号之间的内容。看这个例子:
void foo()
{
int i = 0;
[]()
{
i += 2;
}
}
Here the lambda does not capture anything, thus it will not have access to the enclosing scope, and will not know what i
is. Now, let's capture everythingby reference:
这里 lambda 不捕获任何东西,因此它无法访问封闭的范围,也不知道是什么i
。现在,让我们通过引用捕获所有内容:
void foo()
{
int i = 0;
[&]()//note the &. It means we are capturing all of the enclosing variables by reference
{
i += 2;
}
cout << 2;
}
In this example, the i
inside the lambda is a reference to the i
in the enclosing scope.
在这个例子中,i
lambda的内部是i
对封闭作用域中的的引用。
In your example, you have a lambda inside a member-function of an object. You are trying to call the object's function: setValues(v)
, but your capture list is empty, so your lambda does not know what setValues
is. Now, if you capture this
in the lambda, the lambda will have access to all of the object's methods, because setValues(v)
is the same as this->setValues(v)
in your case, and the error will be gone.
在您的示例中,您在对象的成员函数中有一个 lambda。您正在尝试调用对象的 function: setValues(v)
,但您的捕获列表是空的,因此您的 lambda 不知道是什么setValues
。现在,如果您this
在 lambda 中捕获,则 lambda 将可以访问对象的所有方法,因为setValues(v)
与this->setValues(v)
您的情况相同,并且错误将消失。