【发布时间】:2011-08-06 12:29:09
【问题描述】:
我尝试使用 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 上无法编译,报告的错误以上面的 cmets 给出——我认为原因是在创建 A 之前,它需要实例化 Base 模板,但这反过来又需要知道 A .
在使用 CRTP 时,有没有一种很好的方法可以传入“命名”模板参数?
【问题讨论】:
-
只是为了确认,您认为是对的 :) 这确实是因为您的提议在尝试实例化
A时会导致无限递归。
标签: c++ templates named-parameters crtp