문제

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