1

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:
        ....
}
Lei
  • 51
  • 6
  • Your question seems to be misformatted – Massa Apr 30 '14 at 20:30
  • 8
    Are you asking what [CRTP](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) is? – PeterT Apr 30 '14 at 20:31
  • 1
    I dont know what CRTP is, and why we use this pattern to declare class? Thanks! – Lei Apr 30 '14 at 20:39
  • You really need to examine a use case to understand the why of it. In isolation, it will all seem very abstract and hypothetical. – kec Apr 30 '14 at 20:42
  • @PeterT I find this [post](http://stackoverflow.com/questions/4173254/what-is-the-curiously-recurring-template-pattern-crtp?answertab=votes#tab-top) which answered my question why. Thanks! – Lei Apr 30 '14 at 21:02

2 Answers2

4

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.

Community
  • 1
  • 1
Stefan
  • 1,131
  • 2
  • 12
  • 30
0

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.

Rakib
  • 7,435
  • 7
  • 29
  • 45