Here is the code I don't understand
#include<iostream> using namespace std; template <typename T> T calc(T, T) { cout << "template calc" << endl; } double calc(double, double) { cout << "ordinary calc" << endl; } template <> char calc<char>(char, char) { cout << "template specialisation calc" << endl; } int main() { int ival; double dval; float fd; calc(0, ival); // calls the generic calc(T, T) // the following all call calc(double, double) calc(0.25, dval); calc(0, fd); calc(0, 'J'); calc('I', 'J'); // calls calc(char, char) }
There are 5 function calls to calculate, so I will call them as 1) - 5) depending on their position.
1) makes sense. 0 is an integer, ival is an integer, it makes sense that calc (T, T) is called. Altho, I feel that my reasoning is that it is wrong. In the end, they both double, so if you call calc (double, double), that also makes sense. Therefore, seek clarification here.
2) there are no drams, both are doubled, cause calc (double, double). Plain.
3) fd is a float. You can either call calc (T, T) or calc (double, double). Because 1) led to a call to calc (T, T), I would assume that this will also be the case here, since we again have one parameter equal to 0, but this calls calc (double, double). So it bothers me, especially the difference between this and 1)
4). My first thought was 0 a valid character, so "J", so it calls calc (char, char). It can call calc (T, T) using the generic integer type. But no, both are wrong, it calls calc (double, double). I am very confused about this. It makes no sense to me.
5) it makes sense, but only if I apply the same logic as for 4), which was not true in 4), so if I saw another example of using templates, I would not be sure which logic to apply .
Look for an explanation of why this program does what it does.
Thanks.