【问题标题】:Template method specialization for template type模板类型的模板方法特化
【发布时间】:2015-10-07 12:32:28
【问题描述】:

有这样的模板类(我的意思是简化了):

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

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

是否有可能(以及如何?)专门化方法Wrapper&lt;Array&lt;TYPE&gt;&gt;::DoSomething()

我的意思是,我可以通过定义将这个方法专门用于int 类型:

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

但是我如何专门针对 Array 而保持 Array 不专门? 当然,我可以写:

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

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

我尝试过类似的东西

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

但我有编译错误。

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

【问题讨论】:

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


    【解决方案1】:

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

    有了这个,你可以部分专精DoSomethingHelper

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2010-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多