Search code examples
c++templatesauto

Can we use auto keyword instead of template?


Can we use auto keyword instead of template?

Consider following example :

#include <iostream>

template <typename T>
T max(T x, T y) // function template for max(T, T)
{
    return (x > y) ? x : y;
}

int main()
{
    std::cout << max<int>(1, 2) << '\n'; // instantiates and calls function max<int>(int, int)
    std::cout << max<int>(4, 3) << '\n'; // calls already instantiated function max<int>(int, int)
    std::cout << max<double>(1, 2) << '\n'; // instantiates and calls function max<double>(double, double)

    return 0;
}

So we can write it this way too :

#include <iostream>


auto max(auto x, auto y) 
{
    return (x > y) ? x : y;
}

int main()
{
    std::cout << max(1, 2) << '\n';
    std::cout << max(4, 3) << '\n';
    std::cout << max(1, 2) << '\n';

    return 0;
}

So, why should use auto keyword instead of template?


Solution

  • Finally I found the answer to my question: We can use abbreviated function templates if we're using the C++20 language standard. They are simpler to type and understand because they produce less syntactical clutter.

    Note that our two snippets are not the same. The top one enforces that x and y are the same type, whereas the bottom one does not.