Skip to content

Template Parameters

Template Parameters

A template defines a family of functions and classes. A template by itself is not a type, or a function, or any other entity. No code is generated from a source file that contains only template definitions.

In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function (or class, from a class template).

Templates allow us to reuse the logic of algorithms for different data types. Without templates, our alternative for generic algorithms would be type erasing types.

1
int max(int n1, int n2) { return (n1 > n2) ? n1 : n2; }

1
template <class T> T max(T n1, T n2) { return (n1 > n2) ? n1 : n2; }

1
2
3
template <class T1, class T2> T2 max(T1 n1, T2 n2) {
    return (n1 > n2) ? n1 : n2;
}

1
2
3
std::cout << "max: " << max(3, 9) << '\n';
std::cout << "max: " << max(3.5, 9.3) << '\n';
std::cout << "max: " << max(3, 9.3) << '\n';

1
2
3
4
5
6
// The "old" way: max operating on nullified pointers
void *max(void *n1, void *n2, bool (*comp)(void *, void *)) {
    // `comp` is responsible to internally convert `void*` to the appropriate
    // data type and perform the comparison.
    return (comp(n1, n2)) ? n1 : n2;
}

1
2
// The "old" way: an extra function operating on the nullified pointers
bool comp(void *a, void *b) { return (*(int *)a < *(int *)b); }

1
2
3
4
5
6
// In old C++ and C, we need nullify pointers to create generic functions.
// It's easy to see why this is inconvenient.
int a = 3;
int b = 9;
void *m = max(&a, &b, &comp);
std::cout << "m: " << *(int *)m << '\n';

1
2
3
4
template <class T1, class T2> struct pair {
    T1 first;
    T2 second;
};

1
2
3
pair<int, double> p{3, 3.3};
std::cout << "p.first: " << p.first << '\n';
std::cout << "p.second: " << p.second << '\n';

Share Snippets