Search code examples
c++functiontemplatesc++20auto

Is auto for function input parameters a replacement for function templates?


In C++20 the auto keyword can be used for function input parameters. Is this a proper replacement for function templates and are there any practical differences to consider when deciding on which approach to take?

template <typename T>
void myFunction(T& arg)
{
    // ...
}

vs.

void myFunction(auto& arg)
{
    // ...
}

Related to and borrowed code from this old question.


Solution

  • For a function with one argument, there is no difference. With multiple arguments, auto is considered independently for each of them, i.e.

    template <typename T>
    void myBinaryFunction(T& arg1, T& arg2);
    

    has no simple equivalent with auto, because arg1 and arg2 must deduce to the same type.

    Similarly, non-type template parameters can't be auto

    template <template <typename...> class Container, size_t N>
    void convert(const std::array<int, N> & src, Container<int> & dest);
    

    Nor can type parameters that are not present in the parameters

    template <typename T>
    T getById(int id);