使用奇怪循环模板模式(CRTP)和其他类型参数

Use Curiously Recurring Template Pattern (CRTP) with additional type parameters

本文关键字:CRTP 类型参数 其他 模式 循环      更新时间:2023-10-16

我尝试使用奇怪循环模板模式(CRTP)并提供额外的类型参数:

template <typename Subclass, typename Int, typename Float>
class Base {
    Int *i;
    Float *f;
};
...
class A : public Base<A, double, int> {
};

这可能是一个bug,更合适的超类应该是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时,是否有一个很好的方法来传递"命名"模板参数?

你可以使用一个trait类:

// 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> 
{
};

@James的回答显然是正确的,但是如果用户没有提供正确的typedefs,您仍然可能遇到一些问题。

使用编译时检查工具可以"断言"使用的类型是。根据您使用的c++版本,您可能必须使用Boost。

在c++ 0x中,这是结合:

  • static_assert:一个用于编译时检查的新工具,它允许您指定消息
  • type_traits头,它提供了一些谓词,如std::is_integralstd::is_floating_point

的例子:

template <typename TDerived>
struct Base
{
  typedef typename BaseTraits<TDerived>::IntType IntType;
  typedef typename BaseTraits<TDerived>::FloatType FloatType;
  static_assert(std::is_integral<IntType>::value,
    "BaseTraits<TDerived>::IntType should have been an integral type");
  static_assert(std::is_floating_point<FloatType>::value,
    "BaseTraits<TDerived>::FloatType should have been a floating point type");
};

这与运行时世界中典型的防御性编程习惯用法非常相似。

实际上你甚至不需要trait类。

template 
<
   typename T1, 
   typename T2, 
   template <typename, typename> class Derived_
>
class Base
{
public:
   typedef T1 TypeOne;
   typedef T2 TypeTwo;
   typedef Derived_<T1, T2> DerivedType;
};
template <typename T1, typename T2>
class Derived : public Base<T1, T2, Derived>
{
public:
   typedef Base<T1, T2, Derived> BaseType;
   // or use T1 and T2 as you need it
};
int main()
{
   typedef Derived<int, float> MyDerivedType;
   MyDerivedType Test;
   return 0;
}