除非它在捕获列表中,否则无法在lambda体中引用封闭函数局部变量

use*_*741 29 c++ lambda function

我有json :: value对象,我尝试在结构中获取值,但我得到关于捕获列表的这个错误.我明白在那句话中这个bracet []拥有捕获列表,但我无法弄清楚如何.我如何在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();

}
Run Code Online (Sandbox Code Playgroud)

Sin*_*all 59

捕获列表是放在方括号之间的.看看这个例子:

void foo()
{
    int i = 0;
    []()
    {
        i += 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里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;
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,ilambda内部是i对封闭范围内的引用.

在您的示例中,您在对象的成员函数内部有一个lambda.你试图调用对象的函数:setValues(v),但你的捕获列表是空的,所以你的lambda不知道是什么setValues.现在,如果你this在lambda中捕获,lambda将可以访问所有对象的方法,因为setValues(v)它与this->setValues(v)你的情况相同,并且错误将消失.

  • 不适用于我的问题。收到以下消息:_不存在从“lambda []void ()-&gt;void”到“void (*)()”的合适转换函数_ (4认同)
  • 非常感谢你我理解这个概念.为了宣传所有我应该使用[this]. (3认同)