C++ template

chuuuing
2 min readMar 25, 2021

A Template let the compiler “write” codes for you based on the given rules. Concrete code is only created in compilation ONLY when the template class/function is called(with the given argument).

Concept

To declare a template (of class/function), we use the following syntax:

template <parameter-list> declaration

The “declaration” could be a normal class or function declaration. A concrete example here:

The compiler generates a function out of the template with the specified type.

  • it increases the compilation time
  • generated function is locally scoped in the compilation unit
  • might lead to horrible compile-time-errors if incorrect template arguments are used
The compiler constructs different functions according to the usage.

3 types of template parameter

Template Initialization

  • Explicit initializaiton
  • Implicit initializaiton

Template Specialization

Sometimes we need to modify the template for specific template arguments, for that, we use Template Specialization.

  • the Specialization Template has to appear after the Original Template

Full Specialization: specialized all the parameter in Template. All types of the template can be fully specialized.

template <> declaration<argument list>

Example:

template <typename T> class MyContainer {
// original template
};
template <> class MyContainer<bool> {
// specialized template for BOOL
};

Partial Specialization: only specialized some parameter. Only Class-Template can be partially specialized.

template <non-specialized-parameter-list> declaration<argument-list>

Example:

template <typename C, typename T> class MyContainer {
// original template
};
template <typename T> class MyContainer<std::vector, T> {
// specialized template for only typename C
};

--

--