How to write curiously recurring templates with more than 2 layers of inheritance?
- by Kyle
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")?