Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 171 ยท Templates and Generic Programming

Class Templates

Learn C++ class templates - build a generic Stack<T>, define members outside the class, use class template argument deduction and non-type parameters.

A function template lets one function work with many types. A class template does the same for a whole type: you write the class once, with a placeholder for the element type, and the compiler stamps out a real class for every type you use it with. std::vector<int>, std::vector<std::string> and std::map<std::string, double> are all instances of class templates from the standard library.

In this lesson you'll build a generic Stack<T> from scratch, learn the slightly unusual syntax for defining its members outside the class body, see how C++17's class template argument deduction (CTAD) lets you skip the angle brackets, and use non-type template parameters to bake values such as sizes into a type. By the end you'll be able to read the declarations in standard headers and write reusable containers and wrappers of your own.

Your first class template

A class template starts with template <typename T> followed by an ordinary class definition. Inside the class, T is a type like any other: you can store a std::vector<T>, take const T& parameters and return T.

C++ A generic Stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Stack on its own is not a type. It's a recipe. Stack<int> and Stack<std::string> are two completely separate classes the compiler generated from that recipe; they share no code and you can't assign one to the other. Generating a class from a template is called instantiation, and the type you supply (int) is the template argument.

Unlike function templates, class templates traditionally need the argument spelled out, because there are no function arguments to deduce it from. (CTAD, later in this lesson, relaxes that.) Inside the class body, though, you may write plain Stack as shorthand for Stack<T>; this is the injected class name:

C++
template <typename T>
class Stack {
public:
    Stack& push(const T& value);   // Stack here means Stack<T>
    bool operator==(const Stack&) const = default;
};

Only what you use gets compiled

A member function of a class template is instantiated only if it's used. That's why std::vector<T> can have operator< even for types that can't be compared: as long as you never call it, nothing goes wrong. The same applies to your own templates. If Stack<T> had a print() member that called std::println("{}", item), you could still create a Stack<SomeUnprintableType> and use push and pop; you'd only get an error if you called print().

The flip side: the compiler only fully checks a template's code when it's instantiated. A typo inside a member you never call might not be reported until someone calls it. Exercise every member in a test.

Defining members outside the class

For short members, defining them inside the class is fine. For longer ones you may prefer to keep the class body as a readable summary and define the members below it. Each out-of-class definition must repeat the template header and qualify the name with Stack<T>:::

C++ Members defined outside the class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice three details:

  • The return type comes before Stack<T>::, so it isn't in the class's scope yet. If a member returned a nested type, you'd write typename Stack<T>::Node* or use a trailing return type: auto Stack<T>::find() -> Node*.
  • for_each is a member template: a template inside a template. Its definition needs both headers, outer first.
  • const must match exactly between declaration and definition, as with any class.

Class templates live in headers

Because the compiler needs a template's full definition at the point of instantiation, class templates (including their out-of-class member definitions) go in the header, not in a .cpp file. If you put Stack<T>::push in stack.cpp, other files that include stack.h will compile but fail to link with "undefined reference to Stack<int>::push". The usual layouts are: everything in the class body, or definitions below the class in the same header. See Header Files and Multiple Source Files for the background on linking.

Class template argument deduction (CTAD)

Since C++17, when you create an object and pass constructor arguments, the compiler can deduce the class template's arguments from them, just as it does for function templates:

C++
std::vector v{1, 2, 3};          // std::vector<int>
std::pair p{"pi", 3.14};         // std::pair<const char*, double>
std::array a{1.0, 2.0, 3.0};     // std::array<double, 3>
std::optional o{42};             // std::optional<int>

Your own templates get this for free when a constructor's parameters mention T. When the constructor's parameters don't map directly to T (for example, a pair of iterators), you can add a deduction guide, which tells the compiler "when you see these constructor arguments, deduce these template arguments":

C++ CTAD and a deduction guide

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Without the second guide, Box c{"hello"} would deduce Box<const char*>, storing a pointer instead of a string. That's a common CTAD surprise, also seen with std::vector v{"a", "b"} (a vector of const char*).

CTAD pitfalls to know:

  • Braces prefer initializer lists. std::vector v{5, 1} is std::vector<int> with the two elements 5 and 1, but std::vector v(5, 1) is five copies of 1.
  • Copy deduction wins. std::vector v{other_vector} deduces std::vector<int> (a copy), not a vector of vectors.
  • It's all-or-nothing. You can't deduce some arguments and supply others: std::array<int> a{1, 2} is an error.

When the deduced type isn't obvious to a reader, spell it out. CTAD is a convenience, not a requirement.

Non-type template parameters

Template parameters don't have to be types. A non-type template parameter (NTTP) is a compile-time value: an integer, an enum, a pointer, and since C++20 also a floating-point number or a simple class type ("structural" types with all-public members). The size in std::array<int, 5> is one.

A fixed-capacity stack is a good use: the capacity becomes part of the type, the storage lives inside the object (no heap allocation), and the compiler can check sizes at compile time.

C++ A fixed-capacity stack with a size parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Everything about Capacity is known at compile time. FixedStack<int, 3> and FixedStack<int, 100> are different types with different sizes (24 and 408 bytes here: the array plus an 8-byte count, with 4 bytes of padding after the 12-byte array in the small one). The static_assert rejects FixedStack<int, 0> before the program even exists. The arguments must be constant expressions: FixedStack<int, n> with a runtime n doesn't compile; use std::vector for sizes known only at run time.

Counter shows default template arguments, which work like default function arguments: trailing parameters can have defaults, and Counter<> uses all of them. The standard library uses defaults heavily; std::vector<T> is really std::vector<T, std::allocator<T>>.

Static members, friends and aliases

A few more things behave specially in class templates:

  • Static data members are per instantiation. Stack<int> and Stack<double> each get their own copy of a static int count. Declare it inline static inside the class (C++17) and you don't need a separate definition.
  • Alias templates give a template a shorter name: template <typename T> using Grid = std::vector<std::vector<T>>; then Grid<int>. See Type Aliases: using and typedef.
  • Friend functions defined inside a class template (the "hidden friend" pattern) are the easiest way to give each instantiation its own operator<< or operator==.
C++ Per-instantiation statics and a hidden friend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

When a class template is the right tool

Reach for a class template when a type's structure is the same for many element types: containers, smart pointers, wrappers (Box<T>, Result<T>), matrices, or a cache keyed by any type. If only one or two member functions vary, a regular class with function templates may be simpler. And if behavior must change at run time, virtual functions are the tool: templates are resolved entirely at compile time. To customize a template for one particular type, see Template Specialization; to restrict which types are allowed with readable errors, see Concepts and Constraints.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given template <typename T> class Stack { ... };, which statement is true?

    Each instantiation is a separate class. Stack alone is a template, not a type, and there is no conversion between instantiations unless you write one.
  2. 2. How do you define the member T pop(); of Stack<T> outside the class?

    The definition repeats the template header and qualifies the name with Stack<T>::. The return type T comes first.
  3. 3. What type does std::vector v{"red", "green"}; deduce?

    String literals decay to const char*, so CTAD deduces a vector of pointers. Use std::vectorstd::string (or a deduction guide in your own types) to store strings.
  4. 4. template <typename T, std::size_t N> class FixedStack; Which line compiles if n is an int read from std::cin?

    Non-type template arguments must be compile-time constants. A value read at run time can't be part of a type.
  5. 5. You put a class template in stack.h and its member definitions in stack.cpp. What typically happens when main.cpp uses Stack<int>?

    The compiler needs the template definitions where Stack<int> is instantiated. stack.cpp never instantiated Stack<int>, so the linker finds nothing.

Summary

  • A class template (template <typename T> class Stack) is a recipe; each set of template arguments instantiates a separate class.
  • Member functions are instantiated only when used, and the compiler fully checks template code only on instantiation.
  • Out-of-class members repeat the template header and use Stack<T>::; member templates need two headers. Keep all of it in headers.
  • CTAD (C++17) deduces template arguments from constructor arguments; deduction guides fix cases like iterator pairs or string literals. Watch out for braces and const char*.
  • Non-type template parameters bake compile-time values (sizes, flags) into the type; template parameters can have defaults.
  • Static members are per instantiation, hidden friends give each instantiation its own operators, and alias templates shorten long names.

Next: Template Specialization, where you'll customize a template for specific types.