我尝试使用 Curiously Recurring Template Pattern (CRTP) 并提供额外的类型参数:
template <typename Subclass, typename Int, typename Float>
class Base {
Int *i;
Float *f;
};
...
class A : public Base<A, double, int> {
};
这可能是一个错误,更合适的超类应该是Base<A, double, int>
——尽管这种参数顺序不匹配并不那么明显。如果我可以在 typedef 中使用 name 参数的含义,这个 bug 会更容易看出:
template <typename Subclass>
class Base {
typename Subclass::Int_t *i; // error: invalid use of incomplete type ‘class A’
typename Subclass::Float_t *f;
};
class A : public Base<A> {
typedef double Int_t; // error: forward declaration of ‘class A’
typedef int Double_t;
};
但是,这不能在 gcc 4.4 上编译,报告的错误在上面的注释中给出——我认为原因是在创建 A 之前,它需要实例化 Base 模板,但这反过来又需要知道 A。
在使用 CRTP 时是否有一种很好的方法来传递“命名”模板参数?