Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
Dylan Avatar asked Feb 04 '13 21:02

Dylan


1 Answers

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:
};
like image 76
Pubby Avatar answered Sep 29 '22 16:09

Pubby