简体   繁体   English

提供特征 class 的类型的模板特化

[英]Template specialization for types providing a traits class

I have a class我有一个 class

template <typename T> struct Dispatch;

which is used to call a type-specific function.它用于调用特定类型的 function。 For instance, assume I have dispatchers like例如,假设我有像这样的调度员

template <> struct Dispatch <MyClass> {
  static void Apply (void* a, MyClass& m)
  {
      ::memcpy (a, &m, sizeof (m));
  }
};

Now I have a bunch of classes for which I have a type-trait, ArrayTypes .现在我有一堆类,我有一个类型特征ArrayTypes I would like to do something like:我想做类似的事情:

 template <> struct Dispatch <enable_if<IsArrayType>>
 {
   template <typename ArrayType>
   static void Apply (void* a, ArrayType& m)
   {
     ::memcpy (a, &m, ArrayTypeTraits<ArrayType>::GetSize (m));
   }
 };

Is this possible?这可能吗?

Use boost enable_if .使用升压enable_if

If boost is unavailable, check out the enable_if idiom .如果 boost 不可用,请查看enable_if idiom

Just found it:刚找到:

template <typename T, class Enable = void> struct Dispatch;
template <typename T>
struct Dispatch<T, typename boost::enable_if< typename IsArrayType<T>::type>::type>
{
};

Thanks to Kornel.感谢科内尔。

As of C++14 this is standardized as std::enable_if .从 C++14 开始,这被标准化为std::enable_if

The idea behind traits is that you can provide a default implementation, and types can optionally specialize that.特征背后的想法是您可以提供默认实现,并且类型可以选择专门化它。 This way, you have no special cases in the code that uses the traits.这样,您在使用特征的代码中就没有特殊情况了。 Your approach (having special cases for classes with and without traits defined) defeats the purpose of type-traits.您的方法(对定义有和没有定义特征的类有特殊情况)违背了类型特征的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM