Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Types and Language Concepts

Class templates in C++

Reference for C++ class templates: declaring them, defining members outside the class, default arguments, static members, aliases and specialization.

A class template defines a whole family of classes from one definition. std::vector<int> and std::vector<std::string> are different classes made from the same template. You supply the template arguments in angle brackets, or let the compiler deduce them from constructor arguments (C++17, see class template argument deduction).

Only the members you actually use are instantiated. That allows a class template to contain member functions that would not compile for some types, as long as nobody calls them for those types.

C++
template <typename T>
class Box {
    T value_;
public:
    explicit Box(T v) : value_(std::move(v)) {}
    const T& get() const { return value_; }
};

Try it

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.

C++ Specialization, aliases and deduction

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.

Syntax

C++
template <typename T, int N = 8>          // parameters, optionally with defaults
class Name { /* members may use T and N */ };

template <typename T, int N>              // member defined outside the class
R Name<T, N>::member(Params) { ... }

Name<int> obj;                            // use: supply arguments
template <typename T> using Alias = Name<T, 4>;     // alias template
Part Description
Template parameters Types, non-type values (integers, enums, pointers, and class types in C++20), or other templates.
Defaults Later parameters may have defaults; all parameters after the first default must have one. Use Name<> to take all defaults.
Member templates A member function can itself be a template (template <typename U> void add(U)), for converting constructors, for example.
Static members Each instantiation has its own copy of each static data member.
Friend templates template <typename U> friend class Other; grants access to all instantiations.

Usage notes

  • Inside the class the name Name (the injected-class-name) means Name<T, N>. Outside it, write the full Name<T, N>.
  • Out-of-class members repeat the template <...> header and qualify with Name<T, N>::.
  • Dependent names need typename. If the type is T::iterator, write typename T::iterator. Calling a member template of a dependent object may need obj.template foo<int>().
  • Inheritance from a dependent base: members of Base<T> are not found by unqualified lookup. Write this->x, using Base<T>::x; or Base<T>::x.
  • Lazy instantiation. Declaring Stack<Foo> instantiates the class definition, but member function bodies only when used. This is why std::vector<NoDefaultCtor> works until you call resize.
  • Headers. Put the whole definition in the header, or use explicit instantiation (template class Stack<int>;) in one source file.
  • Specialization: a full specialization is an ordinary class (template <>), a partial one still has parameters. Class templates can be partially specialized, function templates cannot. See template specialization.
  • std::vector<bool> is a famous specialization that behaves differently from the general template: elements are packed bits and operator[] returns a proxy.
  • Constraints (template <std::copyable T> class Box) document and enforce requirements on T.
  • Compile-time cost: template-heavy code increases build time; keep rarely changing instantiations in a single translation unit with extern template.