Using a member of a derived type in a CRTP class

I have a curiously repeating boilerplate template class and a derived class, for example:

template<class Derived>
class A {
  typedef typename Derived::C D;
  D x;
};
class B : public A<B> {
public:
  class C { };
};

This cannot be compiled due to the fact that B will not be fully defined when the compiler tries to determine D. How can I achieve a similar result, that is, to have elements of A that have a type defined in B? Or do I need to get C to define outside B?

+5
source share
1 answer

Or do I need to get C to define outside B?

Yes, unfortunately, you need to do this. You can usually define the template class to Aand specialize it for the Bcontaining type C. This allows you to use it in A.

template<typename T>
struct members;

template<class Derived>
class A {
  typedef typename members<Derived>::C D;
  D x;
};

template<>
struct members<class B> {
  class C { };
};
class B : public A<B> {
public:
};
+8
source

All Articles