jeudi 29 octobre 2015

Template method specialization for multiple types

I have a class “A” which exposes the template method foo. Foo has a standard implementation which works fine with B,C. It also has a special implementation for D.

class A
{
  template<typename T>
  void foo()
  {
    //standard implementation
  }

  template<>
  void foo<D>
  {
    //special implementation
  }
}

class B{};
class C{};
class D{};

int main()
{
  A<B> a1;
  A<C> a2;
  A<D> a3;
}

Now, I need to add the class E, which requires for "foo" the same special implementation as D. Is there a way to say something like: For all the types use the standard foo. For D,E (and so on) the special implementation.

class A
{
  template<typename T>
  void foo()
  {
    //standard implementation
  }

  template<>
  void foo<D && E>  <-- PseudoCode - It doesn't work
  {
    //special implementation
  }
}

class B{};
class C{};
class D{};
class E{};

int main()
{
  A<B> a1;
  A<C> a2;
  A<D> a3;
  A<E> a4;
}

I was thinking to use the trait classes. But I was hoping there is something simpler to achieve this. Thanks

Aucun commentaire:

Enregistrer un commentaire