an enclosing-function local variable cannot be referenced in a lambda body unless if it is in capture list
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 everything by reference:
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.
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.
Related videos on Youtube
user2957741
Updated on July 09, 2022Comments
-
user2957741 almost 2 years
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?
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(); }
-
user2957741 over 9 yearsthis is fixed when i added [this] but i try to understand why
-
-
Balazs Kelemen over 2 yearsDoes not work for my problem. Got the following message: no suitable conversion function from "lambda []void ()->void" to "void (*)()" exists