我尝试使用 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 中使用名称参数的含义,那么这个错误会更容易看出:
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 时是否有传递“命名”模板参数的好方法?
您可以使用特征类:
// Must be specialized for any type used as TDerived in Base<TDerived>.
// Each specialization must provide an IntType typedef and a FloatType typedef.
template <typename TDerived>
struct BaseTraits;
template <typename TDerived>
struct Base
{
typename BaseTraits<TDerived>::IntType *i;
typename BaseTraits<TDerived>::FloatType *f;
};
struct Derived;
template <>
struct BaseTraits<Derived>
{
typedef int IntType;
typedef float FloatType;
};
struct Derived : Base<Derived>
{
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)