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

前端 未结 3 1339
挽巷
挽巷 2020-12-09 11:30

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

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

cl         


        
相关标签:
3条回答
  • 2020-12-09 11:52

    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.

    0 讨论(0)
  • 2020-12-09 11:54

    Could you please explain how this works?

    Uhm... it just.. does? The standard specifically allows template parameters to be of incomplete type. And since no method in the CRTP base class needs a fully defined type, everything is fine.

    §3.9.2 p3 [basic.compound]
    Pointers to incomplete types are allowed although there are restrictions on what can be done with them (3.11).

    §14.3.1 p2 [temp.arg.type]
    [ Note: A template type argument may be an incomplete type (3.9). —end note ]

    0 讨论(0)
  • 2020-12-09 11:55

    This is called CRTP. It is used for static polymorphism which can be faster than using virtual.

    : public MyTemplate<MyClass>
    

    Instantiates MyTemplate<MyClass>, although since MyClass is incomplete you can only use T in ways that don't require a complete type. Such as using a pointer or calling a member function.

    Anyway, just look at your snippet, it's essentially the same as this:

    class MyClass
    {
        MyClass* member;
        MyClass* method();
    }
    

    Which is perfectly legal and understandable.

    0 讨论(0)
提交回复
热议问题