I'm trying to understand below sample code I have. I know we can explicitly specify data type but not sure what "int, double" and "int, int" means. And why do we write function template that way instead of T tripleit (T Val) { T temp = val * 3; }? Thanks in advance.
#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;
}
By the way, the output is :
Explicit int; int argument: 15
Explicit int; double argument: 9
Explicit int, double; double argument: 9
Explicit int, int; double argument: 9
If the template parameters had more descriptive names, they could look like this:
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
}
With these names, it should be a bit more clear. The function can be used to multiply a number by 3 and convert it to a desired type at the same time.
Invoking the template with both template arguments specified simply suppresses template argument deduction. I think the really interesting case is missing there:
cout << "Explicit double, int; double argument: " << tripleit<double, int>(d) << '\n';
This will pass in a double
value 3.3
. However, as ParameterType
is explicitly specified to be int
, the value will be converted to int
(perhaps with a warning). Inside the function, temp
will be of type double
(the first template argument), but the return value will still be 9, so the expected output is 9
or perhaps 9.0
or 9.0e0
depending on the current cout
settings for floating-point numbers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.