首页 > 解决方案 > 我们可以使用 auto 关键字代替模板吗?

问题描述

我们可以使用 auto 关键字代替模板吗?

考虑以下示例:

#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;
}

所以我们也可以这样写:

#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;
}

那么,为什么要使用 auto 关键字而不是模板呢?

标签: c++templatesauto

解决方案


正如@HolyBlackCat 在评论中所说,片段不一样。在使用模板的第一个片段中,您将 的参数限制为T max(T x, T y)相同类型。所以如果你采用模板的方式,下面的代码就行不通了:

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

但是,如果您采用第二种方法,则可以比较两种不同的数据类型(当然,如果允许的话)。这是因为两个参数的 auto 都会独立决定它会得到什么,所以在第二种方法中比较 aintdouble是完全有效的。


推荐阅读