gpt4 book ai didi

c++ - 明确指定类型的函数模板

转载 作者:行者123 更新时间:2023-11-30 04:11:10 26 4
gpt4 key购买 nike

我试图理解下面的示例代码。我知道我们可以明确指定数据类型但不确定“int, double”和“int, int”是什么意思。为什么我们要这样写函数模板而不是 T tripleit (T Val) { T temp = val * 3; }?提前致谢。

#include <iostream>

using namespace std;
// why do we write this way instead of T tripleit (T Val) { T temp = val * 3; }?
template <class T, class U>
T tripleit (U val)
{
T temp = val * 3;

}


int main()
{
int a=5;
double d=3.3;

cout << "Explicit int; int argument: " << tripleit<int>(a) << endl;
cout << "Explicit int; double argument: " << tripleit<int>(d) << endl;

// what does <int, double> and <int, int> mean?
cout << "Explicit int, double; double argument: " << tripleit<int, double>(d) << endl;
cout << "Explicit int, int; double argument: " << tripleit<int, int>(d) << endl;

return 0;
}

顺便说一句,输出是:

显式整数;整数参数:15

显式整数;双参数:9

显式 int, double;双参数:9

显式整型,整型;双参数:9

最佳答案

如果模板参数有更多的描述性名称,它们可能看起来像这样:

template <class ReturnType, class ParameterType>
ReturnType tripleit (ParameterType val)
{
ReturnType temp = val * 3;
return temp; // I assume this line is actually present in your code, it makes no sense otherwise
}

有了这些名字,应该更清楚一点了。该函数可用于将数字乘以 3,同时将其转换为所需的类型。

使用指定的两个模板参数调用模板只会抑制模板参数推导。我认为那里缺少真正有趣的案例:

cout << "Explicit double, int; double argument: " << tripleit<double, int>(d) << '\n';

这将传递一个 double3.3。但是,由于 ParameterType 被明确指定为 int,该值将被转换为 int(可能带有警告)。在函数内部,temp 的类型为 double(第一个模板参数),但返回值仍为 9,因此预期输出为 99.09.0e0 取决于 float 的当前 cout 设置。

关于c++ - 明确指定类型的函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20301492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com