Quantcast
Viewing all articles
Browse latest Browse all 5

What are the type conversion rules for parameters and return values of lambdas?

I was recently surprised by the fact that lambdas can be assigned to std::functions with slightly different signatures. Slightly different meaning that return values of the lambda might be ignored when the function is specified to return void, or that the parameters might be references in the function but values in the lambda.

See this example (ideone) where I highlighted what I would suspect to be incompatible. I would think that the return value isn't a problem since you can always call a function and ignore the return value, but the conversion from a reference to a value looks strange to me:

int main() {    function<void(const int& i)> f;    //       ^^^^ ^^^^^    ^    f = [](int i) -> int { cout<<i<<endl; return i; };    //     ^^^    ^^^^^^    f(2);    return 0;}

The minor question is: Why does this code compile and work? The major question is: What are the general rules for type conversion of lambda parameters and return values when used together with std::function?


Viewing all articles
Browse latest Browse all 5

Trending Articles