具有类型的显式规范的函数模板
Function template with explicit specification of type
我正在努力理解下面的示例代码。我知道我们可以显式指定数据类型,但不确定"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';
这将传递一个double
值3.3
。但是,由于ParameterType
被明确指定为int
,该值将被转换为int
(可能带有警告)。在函数内部,temp
的类型为double
(第一个模板参数),但返回值仍为9,因此预期输出为9
,或者可能为9.0
或9.0e0
,具体取决于浮点数的当前cout
设置。
相关文章:
- 具有默认模板类型的默认构造函数的类型推导
- 在 c++ 中将函数返回类型指定为模板参数
- 仅在函数模板中为那些定义了函数的类型执行函数
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 函数模板返回类型
- 在实例化之前推断函数模板的返回类型
- 如何调用模板类型的正确构造函数?
- 函数模板签名中忽略的成员类型def 的访问说明符
- 实例化多种类型的成员函数模板
- 如何避免模板函数返回类型重复?
- 使用函数模板推导返回类型
- 重载模板<类型名...>类的函数模板
- 专用于类型集的函数模板
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- async中没有匹配的函数(模板中未解析的类型)
- 如何在C++中根据函数模板类型应用不同的 #define?
- 从函数模板类型中提取返回类型
- 在 c++11 中,当参数类型为常量左值引用与非常量左值引用时,函数模板类型推导的工作原理
- 括号初始化列表和函数模板类型演绎顺序