7

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?

Dylan
  • 1,692
  • 1
  • 13
  • 24

1 Answers1

11

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:
};
Pubby
  • 51,882
  • 13
  • 139
  • 180
  • 1
    Thanks for the answer and good example. Also I think a `public:` or `friend class A;` is required in `members` to actually allow `A` to use `C`. – Dylan Feb 05 '13 at 10:07
  • @Dylan Yeah, I meant to make `members` a struct to get the public access. – Pubby Feb 05 '13 at 19:12