January 2019
Intermediate to advanced
512 pages
14h 5m
English
Once we have deduced the template parameter types, type substitution is a purely mechanical process:
template <typename T> T* f(T i, T& j) { j = 2*i; return new T(i); }int i = 5, j = 7;const int* p = f(i, j);
In this example, the T type can be deduced from the first argument as int. It can also be deduced from the second argument, also as int. Note that the return type is not used for the type deduction. Since there is only one possible deduction for T, we now proceed to substitute T with int every time we see T in the function definition:
int* f(int i, int& j) { j = 2*i; return new int(i); }
Not all types, however, are created equal, and some allow more liberties than others. Consider this code:
template <typename T> ...