Home > OS >  Can we use auto keyword instead of template?
Can we use auto keyword instead of template?

Time:11-10

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?

CodePudding user response:

As @HolyBlackCat said in the comment, the snippets are not the same. In the first snippet when you use templates, you confine the arguments of T max(T x, T y) to be of the same type. So if you take the template approach, the following code will not work:

int x = 3;
double y = 5.4;
max(3, 5.4);

However, if you take the second approach, you can compare two different data types (if permitted, of course). This is because both argument's auto will decide what it's going to get independently, so comparing a int and double in the second approach is totally valid.

CodePudding user response:

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.

  • Related