[英]a function template having a return type, which cannot be deduced from arguments
显式模板参数规范的总和
template<class T>
T max(T t1, T t2)
{
if (t1 > t2)
return t1;
return t2;
}
max<double>(120, 14.55); we explicitly determine the type of T as double
下面,它有点不同
template<class T>
T SumOfNumbers(int a, int b)
{
T t = T(); // ???
t = T(a)+b; //???
return t;
}
这需要两个整数,并总结它们。 虽然,在int本身中对它们求和是合适的,但是这个函数模板提供了根据调用者的要求计算任何类型的总和(使用operator +)的机会。 例如,将结果变为double,您可以将其称为:
double nSum;
nSum = SumOfNumbers<double>(120,200); // ???
我理解“显式模板参数规范”主题。 但是,这里条件不同,bcs函数模板的参数'类型已经是明确的。
我无法理解标志“???”之前的线条 ?
你能一步一步地向我解释一下吗? 这条线发生了什么
nSum = SumOfNumbers<double>(120,200);
120转120.0即从int转为double?
什么T(a)? 这是什么意思?
参考文献: http : //www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1
T t = T();
通过值初始化初始化t
。 对于内置算术类型,它的值为零; 对于用户定义的类型,它使用默认构造函数初始化。
(迂腐地,它是通过复制或移动一个初始化的临时值来初始化的,所以如果没有可用的复制或移动构造函数,这将失败;实际上,复制或移动将被省略)。
t = T(a)+b;
将a
转换为类型T
,将b
添加到转换后的值,并将结果赋给t
。 如果T
是内置类型,则T(a)
将使用标准转换或强制转换; 如果它是用户定义的,那么它将使用T(int)
形式的构造函数。
第一行没有意义,因为t
将立即重新分配。 该函数可以更清楚地写为return T(a)+b;
nSum = SumOfNumbers<double>(120,200);
这实例化函数模板,返回类型为double
,并调用。 整体效果与nSum = double(120) + 200;
或者nSum = 220.0
。
T t = T(); // This creates a new object of type T inefficiently though, I think it actually creates a temporary one and then calls the copy-constructor.
nSum = SumOfNumbers<double>(120,200); // This calls your function with type parameter double with parameter 120 and 200. This means it will compile a version of SumOfNumbers where T is "substituted" by double
T(a)
调用T
的构造函数,将int
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.