模板类型的模板方法专门化

GPU*_*ant 4 c++ templates partial-specialization template-specialization

有像这样的模板类(它被简化以获得我的观点):

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

    template <typename TYPE> class Array
    {
       TYPE * m_pArray;
    };
Run Code Online (Sandbox Code Playgroud)

是否有可能(以及如何?)专门化方法Wrapper<Array<TYPE>>::DoSomething()

我的意思是,我可以int通过定义来专门化这种类型的方法:

    template <> void Wrapper<int>::DoSomething(){...};
Run Code Online (Sandbox Code Playgroud)

但是我如何专注于此Array但保持Array不专业?当然,我可以写:

    template <> void Wrapper<Array<int>>::DoSomething(){...}; 
Run Code Online (Sandbox Code Playgroud)

但这根本不是通用的,与模板的优势相矛盾.

我尝试过类似的东西

    template <typename T> void Wrapper<Array<T>>::DoSomething(){...};
Run Code Online (Sandbox Code Playgroud)

但我有编译错误.

我想知道这样做的正确方法是什么?谢谢

Rei*_*ica 6

不,C++不支持函数模板的部分特化,你想要的是函数模板的有效部分特化.但是,在这些情况下,您可以经常使用"委托给类"技巧.

改变这样的原始实现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*/
  }
};
Run Code Online (Sandbox Code Playgroud)

有了这个,您可以部分专业化DoSomethingHelper:

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