Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a class inherit from a template based on itself?

While reading an article, I came across the following syntax:

template <typename T>
class MyTemplate
{
    T* member;
    T* method();
    // ...
}

class MyClass : public MyTemplate<MyClass>
{
    // ...
}

I don't exactly understand how MyClass can inherit from a template that's based on itself. Could you please explain how this works?

like image 623
Dan Nestor Avatar asked Dec 01 '11 03:12

Dan Nestor


1 Answers

This is called the Curiously Recurring Template Pattern, or CRTP for short. It is used to achieve the effect of static polymorphism by taking advantage of the fact that by the time you get to MyTemplate<MyClass> in the line class MyClass : public MyTemplate<MyClass>, MyClass is semi-defined (it is an incomplete type) so you can store pointers to that type, etc, and do things with it that do not require a complete type.

like image 184
Seth Carnegie Avatar answered Nov 26 '22 04:11

Seth Carnegie