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:
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:
This will pass in a
double
value3.3
. However, asParameterType
is explicitly specified to beint
, the value will be converted toint
(perhaps with a warning). Inside the function,temp
will be of typedouble
(the first template argument), but the return value will still be 9, so the expected output is9
or perhaps9.0
or9.0e0
depending on the currentcout
settings for floating-point numbers.