Defining member function templates
So far, we have learned about function templates and class templates. It is possible to define member function templates too, both in non-template classes and class templates. In this section, we will learn how to do this. To understand the differences, let's start with the following example:
template <typename T> class composition { public: T add(T const a, T const b) { return a + b; } };
The composition
class is a class template. It has a single member function called add
that uses the type parameter T
. This class can be used as follows:
composition<int> c; c.add(41, 21);
We first need to instantiate an object of the composition
class. Notice that we must explicitly specify the argument for the type parameter T
because the compiler is not able to figure it out by itself (there is no context from which to infer it). When we invoke...