GPUquant
GPUquant

Reputation: 245

Template method specialization for template type

Having template classes like this (it's simplified to get my point):

    template <typename TYPE> class Wrapper
    {
       TYPE m_tValue;
       void DoSomething();
    };

    template <typename TYPE> class Array
    {
       TYPE * m_pArray;
    };

is it possible (and how?) to specialize method Wrapper<Array<TYPE>>::DoSomething()?

I mean, I am able to specialize this method for int type by defining:

    template <> void Wrapper<int>::DoSomething(){...};

But how do I specialize this for Array but keeping Array not specialized? Of course, I could write:

    template <> void Wrapper<Array<int>>::DoSomething(){...}; 

but that's not generic at all and contradicts the advantage of templates.

I've tried something like

    template <typename T> void Wrapper<Array<T>>::DoSomething(){...};

but I've got compile errors.

I wonder what is the proper way to do it? thx

Upvotes: 4

Views: 111

Answers (1)

No, C++ does not support partial specialisation of function templates, and what you want is effectively partial specialisation of a function template. However, in these cases, you can often use the "delegate to class" trick.

Change the original implementation of DoSomething like this:

template <typename TYPE> class Wrapper
{
   TYPE m_tValue;
   void DoSomething() { DoSomethingHelper<TYPE>::call(*this); }
};

template <class TYPE>
struct DoSomethingHelper
{
  static void call(Wrapper<TYPE> &self) {
    /*original implementation of DoSomething goes here*/
  }
};

With this, you can partially specialise DoSomethingHelper:

template <class TYPE>
struct DoSomethingHelper<Array<TYPE>>
{
  static void call(Wrapper<Array<TYPE>> &self) {
    /*specialised implementation of DoSomething goes here*/
  }
};

Upvotes: 6

Related Questions