Template Method Specialization for Template Type

The presence of such template classes (this simplified my point of view):

    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 the method Wrapper<Array<TYPE>>::DoSomething()?

I mean, I can specialize this method for a type intby defining:

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

But how do I specialize in Array, but keeping Arraynot specialized? Of course, I could write:

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

but this is not general and contradicts the advantage of templates.

I tried something like

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

but I have compilation errors.

I wonder how to do it right? THX

+4
source share
1 answer

, ++ , , , - . " ".

DoSomething :

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*/
  }
};

DoSomethingHelper:

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

Source: https://habr.com/ru/post/1610577/


All Articles