CRTP Pattern in C++

Level 5516 keystrokes

CRTP (Curiously Recurring Template Pattern): each class derives from Counter<itself>, so Counter<Dog> and Counter<Cat> are different classes with separate static counters. Two Dogs and one Cat give the counts 2 and 1.

C++ code

// Derived is the class that inherits from this template
1template<typename Derived>
2class Counter {
// One counter per instantiation, so each Derived has its own
3 static int count;
4public:
// Counts up when an object is created and down when it is destroyed
5 Counter() { count++; }
6 ~Counter() { count--; }
// Static function: called on the class, e.g. Dog::getCount()
7 static int getCount() { return count; }
8};
9
10template<typename T>
// Defines and initializes the static member for every Counter<T>
11int Counter<T>::count = 0;
12
// CRTP: Dog passes itself as the template argument
13class Dog : public Counter<Dog> {
14public:
15 string name;
16 Dog(string n) : name(n) {}
17};
18
// Cat gets a separate Counter<Cat>
19class Cat : public Counter<Cat> {
20public:
21 string name;
22 Cat(string n) : name(n) {}
23};
24
// Two Dogs: Counter<Dog>::count becomes 2
25Dog d1("Rex"), d2("Max");
// One Cat: Counter<Cat>::count becomes 1
26Cat c1("Whiskers");
// Prints "Dogs: 2"
27cout << "Dogs: " << Dog::getCount() << endl;
// Prints "Cats: 1"
28cout << "Cats: " << Cat::getCount() << endl;

Output

Dogs: 2
Cats: 1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 17
  • :× 15
  • ;× 14
  • (× 12
  • )× 12
  • "× 10
  • {× 8
  • }× 8
  • >× 5
  • -× 2

More C++ examples at level 5

← C++ typing practice