c++ - 我们可以使用 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 关键字而不是模板呢?
解决方案
正如@HolyBlackCat 在评论中所说,片段不一样。在使用模板的第一个片段中,您将 的参数限制为T max(T x, T y)
相同类型。所以如果你采用模板的方式,下面的代码就行不通了:
int x = 3;
double y = 5.4;
max(3, 5.4);
但是,如果您采用第二种方法,则可以比较两种不同的数据类型(当然,如果允许的话)。这是因为两个参数的 auto 都会独立决定它会得到什么,所以在第二种方法中比较 aint
和double
是完全有效的。
推荐阅读
- javascript - 当我尝试设置我的网站图标时,为什么会得到 [object HTMLImageElement]?
- python - 使用迭代将旧字典中的值提取到新字典中
- python - 如何通过用户在 django 模板中显示与反向引用的关系?
- eslint - 为什么在这里找到 require-atomic-updates ?
- r - 无法在 R 中访问 EIA API
- flutter - 从一个页面导航到另一个页面容器 google_maps 会导致黑屏
- python - 通过 python 脚本从 KIWI TCMS 导出测试用例不起作用
- android - 我的 rxAndroid 代码文本视图有什么问题没有更新
- javascript - 如何将粒子系统初始化为球形帽?
- javascript - 打字稿无法识别无类型节点模块的构造函数