質問

I have one class B which inherited from class A, but I dont understand why class B declares in this way.

class B : public A <B>
{
public:
    ...
};

template <class T>
class A
{
public:
        ....
}
役に立ちましたか?

解決

As already pointed out by PeterT, this is the curiously recurring template pattern (CRTP). It is a way to implement static polymorphism in C++ as the base class A has knowledge about the subclass B and its (internal) types and states.

For instance, the logic in A can return objects of the right type which would not be possible with dynamic polymorphism. CRTP allows to move that logic to the base class where dynamic polymorphism would require virtual functions within the derived class to deal with the right type appropriate to B.

A more detailed explanation is given here.

他のヒント

class A is a template class. So while inheriting, B must provide value for the templae argument T, which in this case is 'B'. But you have to place class definition of A before B, otherwise there will be a compile error.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top