문제

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?

도움이 되었습니까?

해결책

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:
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top