C++ auto return type

Viewed 613

I wrote a function that looks like that:

auto fn(auto x) {
    return x;
}

I called it twice with different arguments:

std::cout << fn(3124) << std::endl;
std::cout << fn("hello world") << std::endl;

It works fine, but I don't understand why - I thought the compiler deduces a constant return type for the function - int (due to the first call - fn(3124)). It seems that the compile-time generated function looks like

template<typename T>;
T fn(T x) {
   return x;
}

I can't figure out why. Please explain.

1 Answers
auto fn(auto x)

is a C++20 version of

template<class X>
auto fn(X x)

As such, it would be instantiated for every argument type it was called with, having different return type for each different argument type. That feature is called Abbreviated function template

Related