Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> {
  //...
};
like image 311
Thomson Avatar asked Oct 27 '10 05:10

Thomson


2 Answers

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.

like image 178
GManNickG Avatar answered Sep 20 '22 07:09

GManNickG


I think you are reffering to CRTP. Also refer here

like image 25
Chubsdad Avatar answered Sep 22 '22 07:09

Chubsdad