有这样的模板类(为了理解我的观点而进行了简化):
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/