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

时间:2015-10-07 12:32:29

标签: c++ templates template-specialization partial-specialization

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

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

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

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

我的意思是,通过定义:

,我可以将此方法专门用于int类型
    template <> void Wrapper<int>::DoSomething(){...};

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

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

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

我尝试过像

这样的东西
    template <typename T> void Wrapper<Array<T>>::DoSomething(){...};

但我有编译错误。

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

1 个答案:

答案 0 :(得分:6)

不,C ++不支持功能模板的部分特化,你想要的是功能模板的有效部分特化。但是,在这些情况下,您通常可以使用&#34;委托来分类&#34;特技。

更改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*/
  }
};
相关问题