Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return values from lambdas with auto parameter

I am playing with lambda expressions and I am using auto as input parameter.

I did try this code below

auto f2 = [](auto a){ return a;};
std::cout << f2(10) << std::endl;
std::cout << f2("hi there!") << std::endl;

With my big surprise it compiles and run ok! How is that possible?

If I am not wrong (this comes with the C++14) the operator() of the function object is template since it uses auto as input parameter.

How does it manage multiple return types? First line returns an int and the second line returns const char*.

Is the compiler creating multiple operator() behind the scenes?

like image 523
Abruzzo Forte e Gentile Avatar asked Mar 19 '15 23:03

Abruzzo Forte e Gentile


1 Answers

As you say, the operator() of generic lambda is effectively a function template. Something similar to:

struct noname
{
    template<typename T>
    auto operator ()(T a) const { return a; }
};

Your separate calls instantiate two different functions.

auto operator ()(int a) const { return a; }
auto operator ()(const char* a) const { return a; }

From there, the rules of auto return type apply. In the first function, the first and only return statement returns an int, therefore int is deduced as the return type. Same for const char*

like image 143
eerorika Avatar answered Nov 11 '22 15:11

eerorika