【问题标题】:std::binding to a lambda: compilation errorstd::binding 到 lambda:编译错误
【发布时间】:2018-01-29 19:04:20
【问题描述】:

我在尝试将 std::bind 转换为 lambda 时遇到了错误。以下代码示例编译良好:

#include <functional>
#include <iostream>

int main()
{
    const auto lambda1 = [](int a, int b){ return a + b; };

    std::cout << (std::bind( lambda1, std::placeholders::_1, 2))(2)
              << std::endl;

    return 0;
}

但以下不是:

#include <functional>
#include <iostream>

int main()
{
    const auto lambda2 { [](int a, int b){ return a + b; } }; // Note the "{ }-initialization"

    std::cout << (std::bind( lambda2, std::placeholders::_1, 2))(2)
              << std::endl;

    return 0;
}

这是我使用 Visual Studio 2013,更新 4 得到的错误输出:

1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1>  main.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap(58): error C2064: term does not evaluate to a function taking 2 arguments
1>          C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xrefwrap(118) : see reference to class template instantiation 'std::_Result_of<_Fty,int &,int &>' being compiled
1>          with
1>          [
1>              _Fty=std::initializer_list<main::<lambda_55c00b1d5f4fcd1ad46b46ad921a2385>>
1>          ]
1>          C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\functional(975) : see reference to class template instantiation 'std::result_of<_Funx (int &,int &)>' being compiled
1>          with
1>          [
1>              _Funx=std::initializer_list<main::<lambda_55c00b1d5f4fcd1ad46b46ad921a2385>>
1>          ]
1>          main.cpp(23) : see reference to class template instantiation 'std::_Do_call_ret<false,_Ret,std::initializer_list<main::<lambda_55c00b1d5f4fcd1ad46b46ad921a2385>>,std::tuple<std::_Ph<1>,int>,std::tuple<int &>,std::_Arg_idx<0,1>>' being compiled
1>          with
1>          [
1>              _Ret=void
1>          ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

发生了什么事?似乎与初始化列表有些混淆,但我不确定为什么。

【问题讨论】:

标签: c++ c++11 lambda initializer-list stdbind


【解决方案1】:

之前,auto foo{x}; 创建一个x 类型元素的初始化列表。

const auto lambda2 { [](int a, int b){ return a + b; } };

所以这个lambda2 不是 lambda,它是 lambda 的初始化列表。

这已在 中修复,并且可能作为缺陷追溯应用。很惊喜。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2016-11-13
    • 2021-06-15
    相关资源
    最近更新 更多