Subclass B Inherits from template class A <B>
I recently came across a code that looks like this, and I can't wrap it around:
template<typename T>
class A
{
}
class B: A<B>
{
}
So my general questions are:
- Why does this not give a compilation error? In particular, how does a class
Binherit from a template classA<B>, ifBnot already defined? - When will this structure ever be needed?
+4
1 answer
One of the features: this template template will help you avoid using vtable. This is called "Static Polymorphism" - http://en.m.wikipedia.org/wiki/Curiously_recurring_template_pattern
, :
class Item {
public:
virtual void func() = 0;
}
class A : public Item {
// …
}
class B : public Item {
// …
}
Item *item = new A();
item->func();
:
template<typename T>
class Item {
public:
void func() {
T::func();
}
}
class A : public Item<A> {
// …
}
class B : public Item<B> {
// …
}
Item<A> *item = new A();
item->func();
, . ...
+2