Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function with different signatures from std::function

Tags:

c++

c++11

lambda

I don't understand why the third case is ok (even if the lambda's arguments type is different from the std::function type are) while the compiler complains with the fourth one:

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!
like image 586
justHelloWorld Avatar asked Apr 27 '16 10:04

justHelloWorld


1 Answers

When you write:

function<int(int)> idInt = [](int &i) {return i;}; //ERROR!

then you say that idInt can wrap a function,closure,.. which can be called with int argument. But this is not true in case of [](int &i) {return i;};, because you cannot call it with integral literal like here:

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

you can fix it by changing signature to use rvalue reference or const&:

std::function<int(int)> idInt1 = []( int &&i) {return i;};
std::function<int(int)> idInt2 = []( const int &i) {return i;};
like image 78
marcinj Avatar answered Oct 31 '22 14:10

marcinj