8

What's the purpose of this pattern? What is it called? It looked very strange when I saw it the first time, though I have now seen it many times.

template<typename Derived>
struct Base {
  //...
};

struct Example : Base<Example> {
  //...
};
Thomson
  • 20,586
  • 28
  • 90
  • 134

3 Answers3

10

It's called the Curiously Recurring Template pattern, and allows for static polymorphism.

It's useful when you want to add functionality to a specific class, but want the utility to be usable in a generic case. By making the utility dependent on and use a template parameter, you can achieve both.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
6

Curiously Recurring Template Pattern, or CRTP as we call it.

6

I think you are reffering to CRTP. Also refer here

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
  • @Thomson Tan: Note carefully about @GMan's point about static polymorphism. That's an important point. It provides for simulating virtual function calls from the base class without the overhead of virtual functions (if that is important) – Chubsdad Oct 27 '10 at 07:44