Home > Blogs > 30 C++ Tips in 30 Days: Tip # 27 defining and using a member template

30 C++ Tips in 30 Days: Tip # 27 defining and using a member template

By  Dec 19, 2007

Topics: Programming, C/C++

A member template is a template function declared inside a class, which by itself needn't be a template. This tip shows how to define and use a member template.

Suppose you have an ordinary class C. You want to declare a member function that is a function template of that class. The syntax is pretty straightforward:

class C
{
public:
 template <typename T> T func(const T& r) {return r;} //a member template
};

You can invoke the member template like this:

C c;
c.func(5); //OK, calls the member template
c.func<int>(5); //explicit, calls the member template

Notice that the same name can be used for denoting both a member template function and an ordinary function:

class C
{
public:
 template <typename T> T func(const T& r) {return r;}
 int func(int x) {return x;}
};

In this case, the following call changes its semantics:

c.func(5);//now calls the ordinary function

To invoke the member template function you now need to use the explicit instantiation syntax:

c.func<int>(5);

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed