Lambda function with various signatures from std :: function

I don’t understand why the third case is fine (even if the type of the lambda arguments is different from the type of std::function ), while the compiler complains about the fourth:

 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! 
+6
source share
1 answer

When you write:

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

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

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

you can fix this by changing the signature to use the rvalue or const & link:

 std::function<int(int)> idInt1 = []( int &&i) {return i;}; std::function<int(int)> idInt2 = []( const int &i) {return i;}; 
+8
source

All Articles