Dylan
Dylan

Reputation: 1722

Use of member of derived type in CRTP class

I have a curiously recurring template pattern class and a derived class like so:

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

This fails to compile due to B not being fully defined when the compiler attempts to define D. How can I achieve a similar result, i.e. have members of A that are of a type defined in B? Or do I have to force C to be defined outside of B?

Upvotes: 7

Views: 1749

Answers (1)

Pubby
Pubby

Reputation: 53017

Or do I have to force C to be defined outside of B?

Yes, unfortunately you have to do this. Usually you can define a template class before A and specialize it for B, containing the C type. 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:
};

Upvotes: 12

Related Questions