Template specialization for types that provide a feature class

I have a class

template <typename T> struct Dispatch;

which is used to call a type-specific function. For example, suppose 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 whom I have a type-character 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 it possible?

+5
source share
3 answers

Use boost enable_if .

If boost is not available, check enable_if idiom .

+4
source

Just found:

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

Thanks Cornell.

+4
source

The idea is that you can provide a default implementation, and types can optionally specialize in this. This way, you have no special cases in code that uses traits. Your approach (having special cases for classes with and without certain traits) defeats the purpose of types.

0
source

All Articles