具有std :: function的不同签名的Lambda函数

jus*_*rld 6 c++ lambda c++11

我不明白为什么第三种情况没问题(即使lambda的参数类型与std::function类型不同),而编译器抱怨第四种情况:

function<int(int)> idInt = [](int i) {return i;}; //OK
function<int(int&)> idInt = [](int &i) {return i;}; //OK
function<int(int&)> idInt = [](int i) {return i;}; //OK
function<int(int)> idInt = [](int &i) {return i;}; //ERROR!
Run Code Online (Sandbox Code Playgroud)

mar*_*inj 8

当你写:

function<int(int)> idInt = [](int &i) {return i;}; //ERROR!
Run Code Online (Sandbox Code Playgroud)

然后你说idInt可以包装一个函数,闭包,...可以用int参数调用.但是在这种情况下不是这样[](int &i) {return i;};,因为你不能像这里那样使用整数文字调用它:

auto fn = [](int &i) {return i;};
fn(1); // error - you try to bind temporary to reference
Run Code Online (Sandbox Code Playgroud)

您可以通过更改签名来使用右值引用或const&来修复它:

std::function<int(int)> idInt1 = []( int &&i) {return i;};
std::function<int(int)> idInt2 = []( const int &i) {return i;};
Run Code Online (Sandbox Code Playgroud)