A summation of the Explicit Template Argument Specification
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
I understand the part above.
Below , it is a bit different
template<class T>
T SumOfNumbers(int a, int b)
{
T t = T(); // ???
t = T(a)+b; //???
return t;
}
Which takes two ints, and sums them up. Though, summing them in int itself is appropriate, this function template gives opportunity to calculate the sum (using operator+) in any type as required by caller. For example, the get the result in double, you would call it as:
double nSum;
nSum = SumOfNumbers<double>(120,200); // ???
I understand the topic “Explicit Template Argument Specification”. But , here the condition is different , bcs function template’s arguments’ types are already is definite.
I can’t understand the lines before the sign “???” ?
Could you please explain it to me step by step ? What does happen at this line
nSum = SumOfNumbers<double>(120,200);
Does 120 converted 120.0 namely from int to double ?
What T(a) ? What does it mean?
Reference:
http://www.codeproject.com/Articles/257589/An-Idiots-Guide-to-Cplusplus-Templates-Part-1
Initialises
tby value-initialisation. For built-in arithmetic types, it is given the value zero; for user-defined types, it is initialised using the default constructor.(Pedantically, it’s initialised by copying or moving a value-initialised temporary, so this will fail if no copy or move constructor is available; in practice the copy or move will be elided).
Converts
ato typeT, addsbto that converted value, and assigns the result tot. IfTis a built-in type, thenT(a)will use a standard conversion or cast; if it’s user-defined, then it will use a constructor of the formT(int).There’s no point to the first line, since
tis going to be reassigned immediately. The function could be written more clearly asreturn T(a)+b;This instantiates the function template with a return type of
double, and calls. The overall effect is the same asnSum = double(120) + 200;ornSum = 220.0.