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!
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;};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With