1

I was writing a function that should work in the same way with containers of different types. First I wanted to make it a template function, which is obvious, but then I realized that I don't actually need it to be template, instead I can just pass an argument of type auto to it to achieve the same behavior. This simplified example illustrates the idea:

template<typename Container>
void printTemplate(const Container& container)
{
    for (const typename Container::value_type& element : container)
    {
        std::cout << element << '\n';
    }
}

// The same
void printAuto(const auto& container)
{
    for (const auto& element : container)
    {
        std::cout << element << '\n';
    }
}

What I found interesting about this is the following:

int main()
{
    std::vector<int> ints{1, 2, 3, 4, 5};
    printAuto(ints);
    printAuto<std::vector<int>>(ints); // Template syntax?
    return 0;
}

printAuto() function can be called in exactly the same way as if it was declared a template function, and this is a valid c++20 code. Does it mean that the compiler implicitly evaluates such functions as templates? Are such functions instantiated in the same way as template functions (during the first call for a certain type)?

Alexey104
  • 969
  • 1
  • 5
  • 17
  • 2
    Yes, a function with `auto` in parameter is actually a function template. See [this answer](https://stackoverflow.com/a/74514459/12002570) as a consequence of this fact. – Jason Dec 05 '22 at 13:54

0 Answers0