Thomson
Thomson

Reputation: 21625

What's the use of the derived class as a template parameter?

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> {
  //...
};

Upvotes: 8

Views: 3118

Answers (3)

Chubsdad
Chubsdad

Reputation: 25507

I think you are reffering to CRTP. Also refer here

Upvotes: 6

GManNickG
GManNickG

Reputation: 503973

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.

Upvotes: 10

Roger Pate
Roger Pate

Reputation:

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

Upvotes: 6

Related Questions