具有类型的显式规范的函数模板

Function template with explicit specification of type

本文关键字:函数模板 类型      更新时间:2023-10-16

我正在努力理解下面的示例代码。我知道我们可以显式指定数据类型,但不确定"int,double"answers"int,int"的含义。为什么我们用这种方式编写函数模板,而不是T三元组(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;
}

顺便说一下,输出是:

显式int;int参数:15

显式int;双参数:9

显式int,double;双参数:9

显式int,int;双参数: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,因此预期输出为9,或者可能为9.09.0e0,具体取决于浮点数的当前cout设置。