c – std ::绑定到lambda:编译错误
作者:互联网
我试图std ::绑定到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中得到修复,并可能追溯应用为缺陷.这非常令人惊讶.
标签:stdbind,c,c11,lambda,initializer-list,c++17,c++17 来源: https://codeday.me/bug/20190724/1521950.html