...

/

Defining Member Function Templates

Defining Member Function Templates

Explore member function templates in this lesson.

So far, we have learned about function templates and class templates. It’s possible to define member function templates, too, in both nontemplate classes and class templates. In this lesson, we’ll 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;
}
};
A member function in a template class

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:

Press + to interact
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 ...