CRTP 类中派生类型成员的使用 [英] 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 { };
};
由于在编译器尝试定义 D 时未完全定义 B,因此无法编译.如何获得类似的结果,即 A 的成员属于 B 中定义的类型?还是我必须强制在 B 之外定义 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?
推荐答案
或者我是否必须强制在 B 之外定义 C?
Or do I have to force C to be defined outside of B?
是的,不幸的是你必须这样做.通常您可以在A
之前定义一个模板类,并将其专门用于B
,包含C
类型.这允许您在 A
中使用它.
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:
};
这篇关于CRTP 类中派生类型成员的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!