c++ - 模板类型的模板方法特化

标签 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(){...};

但是我有编译错误。

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

最佳答案

不,C++ 不支持函数模板的偏特化,而您想要的是函数模板的有效偏特化。但是,在这些情况下,您通常可以使用“委托(delegate)给类”技巧。

像这样改变 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*/
  }
};

关于c++ - 模板类型的模板方法特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32992327/

相关文章:

c++ - 如何从 C/C++ 中的给定 URL 获取视频链接

c++ - 命名元组元素

django - 在 Django 应用程序中实现 ReactJS 的最佳方式

c++ - 我可以像这里一样有专门的模板吗?

c++ - 无法用新值覆盖 stringstream 变量

c++ - 用于 Windows 的 python ncreduce

c++ - Sun c++ 编译器的段错误

c++ - 重载模板解析

c++ - 不完整类型的无效使用(类方法特化)

c++ - 我可以将 &std::array<> 作为 void* 传递吗?