结合使用好奇重复模板模式(CRTP)和其他类型参数 [英] Use Curiously Recurring Template Pattern (CRTP) with additional type parameters

查看:115
本文介绍了结合使用好奇重复模板模式(CRTP)和其他类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用好奇重复模板模式(CRTP)并提供其他类型参数:

I try to use the Curiously Recurring Template Pattern (CRTP) and provide additional type parameters:

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中的参数含义,将更容易看到此错误:

This is probably a bug, the more appropriate superclass would be Base<A, double, int> -- although this argument order mismatch is not so obvious to spot. This bug would be easier to see if I could use name the meaning of the parameters in a 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

However, this does not compile on gcc 4.4, the reported errors are given as comments above -- I think the reason is that before creating A, it needs to instantiate the Base template, but this in turn would need to know A.

在使用CRTP时是否有传入命名"模板参数的好方法?

Is there a good way of passing in "named" template parameters while using 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> 
{
};

这篇关于结合使用好奇重复模板模式(CRTP)和其他类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆