How to write curiously recurring templates with more than 2 layers of inheritance?
Posted
by Kyle
on Stack Overflow
See other posts from Stack Overflow
or by Kyle
Published on 2010-05-12T17:00:47Z
Indexed on
2010/05/12
17:04 UTC
Read the original article
Hit count: 195
All the material I've read on Curiously Recurring Template Pattern seems to one layer of inheritance, ie Base
and Derived : Base<Derived>
. What if I want to take it one step further?
#include <iostream>
using std::cout;
template<typename LowestDerivedClass> class A {
public:
LowestDerivedClass& get() { return *static_cast<LowestDerivedClass*>(this); }
void print() { cout << "A\n"; }
};
template<typename LowestDerivedClass> class B : public A<LowestDerivedClass> {
public: void print() { cout << "B\n"; }
};
class C : public B<C> {
public: void print() { cout << "C\n"; }
};
int main()
{
C c;
c.get().print();
// B b; // Intentionally bad syntax,
// b.get().print(); // to demonstrate what I'm trying to accomplish
return 0;
}
How can I rewrite this code to compile without errors (and output "C\nB\n")?
© Stack Overflow or respective owner