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?
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*
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