12

我尝试使用 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 时是否有一种很好的方法来传递“命名”模板参数?

4

3 回答 3

23

您可以使用特征类:

// 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> 
{
};
于 2011-04-15T17:29:23.507 回答
10

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

使用编译时检查工具可以“断言”所使用的类型是正确的。根据您使用的 C++ 版本,您可能必须使用 Boost。

在 C++0x 中,这是通过结合:

  • static_assert: 一种新的编译时检查工具,可以让你指定一条消息
  • type_traits头,它提供了一些谓词,例如std::is_integralorstd::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");

};

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

于 2011-04-15T18:15:50.107 回答
2

实际上,您甚至不需要特征类。以下也有效:

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;
}
于 2013-10-24T12:35:36.280 回答