作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在尝试 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++17 之前, auto foo{x};
创建一个类型为 x
的元素的初始化列表。
const auto lambda2 { [](int a, int b){ return a + b; } };
所以这个 lambda2
不是 lambda,它是 lambda 的初始化列表。
这已在 c++17 中修复并且可能作为缺陷追溯应用。这是非常令人惊讶的。
关于c++ - std::binding to a lambda: 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48508266/
我是一名优秀的程序员,十分优秀!