Use of member of derived type in CRTP class

Deadly 提交于 2019-12-10 14:54:49

问题


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?


回答1:


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:
};


来源:https://stackoverflow.com/questions/14696038/use-of-member-of-derived-type-in-crtp-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!