Class Templates

A class template defines a pattern for any number of classes whose definitions depend on the template parameters. The compiler treats every member function of the class as a function template with the same parameters as the class template.

Class templates are used throughout the standard library for containers (list<>, map<>, etc.), complex numbers (complex<>), and even strings (basic_string<>) and I/O (basic_istream<>, etc.).

The basic form of a class template is a template declaration header followed by a class declaration or definition:

template<typename T>
struct point {
  T x, y;
};

To use the class template, supply an argument for each template parameter (or let the compiler substitute a default argument). Use the template name and arguments the way you would a class name.

point<int> pt = { 42, 10 };
typedef point<double> dpoint;
dpoint dp = { 3.14159, 2.71828 };

In member definitions that are separate from the class definition, you must declare the template using the same template parameter types in the same order, but without any default arguments. (You can change the names of the template parameters, but be sure to avoid name collisions with base classes and their members. See Section 7.8 later in this chapter for more information.) Declare the member definitions the way you would any other definition, except that the class name is a template name (with arguments), and the definition is preceded by a template declaration header.

In the class scope (in the class definition, ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.