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

半腔热情 提交于 2019-12-17 18:56:03

问题


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?


回答1:


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.




回答2:


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.




回答3:


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 ]



来源:https://stackoverflow.com/questions/8336220/how-can-a-class-inherit-from-a-template-based-on-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!