Templates in C++ primer (2)

In the first part of this mini-series we looked at the different types of template parameter and the syntax involved in using them. In this part we’re going to look at two idioms that involve use of templates in C++, both of which have acronyms: CRTP and SFINAE.

Curious Recurring Template Pattern

From the earliest days of the availability of templates for C++ (around the mid-nineties, shortly before the publication of the C++98 standard), CRTP has been so named and known about. The pattern it describes is not difficult to comprehend – a base class has a template type parameter which is the type of a (single) derived class. What does take some explaining is that this has a use case in fully describing compile-time polymorphism (as opposed to run-time polymorphism which uses virtual functions, or compile-time “duck-typing” which is the usual behavior of template type parameters).

Continue reading “Templates in C++ primer (2)”

Templates in C++ primer (1)

Types of template

There are three different types of templated entity in C++, they are:

  • Class templates
  • Function templates
  • Variable templates

Of these, class templates are the most flexible as they can optionally be both fully or partially specialized. Function templates (including member function templates) can be optionally (only) fully specialized. A template declaration or definition differs from a normal declaration or definition by being prefixed with: template<parameters...>

Types of template parameters

There are (again) three different types of template parameters in C++, they are:

Continue reading “Templates in C++ primer (1)”