开发者

Template specialization for types providing a traits class

开发者 https://www.devze.com 2023-03-17 01:23 出处:网络
I have a class template <typename T> struct Dispatch; which is used to c开发者_如何转开发all a type-specific function. For instance, assume I have dispatchers like

I have a class

template <typename T> struct Dispatch;

which is used to c开发者_如何转开发all a type-specific 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. 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.

If boost is unavailable, check out the 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.


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.


As of C++14 this is standardized as std::enable_if.

0

精彩评论

暂无评论...
验证码 换一张
取 消