我想专门化模板类中的特定功能。
例如:
template<class T>
class A
{
public :
void fun1(T val);
void fun2(T val1, T val2);
};
template <class T>
void A<T>::fun1(T val)
{
// some task 1;
}
template <class T>
void A<T>::fun2(T val1, T val2)
{
// some task 2;
}
template <>
void A<char*>::fun2(char* val1, char* val2)
{
// some task 2 specific to char*;
}
当我做这样的事情时,我得到错误说 fun2() 的多重定义 请告诉我为什么这是错误的,以及实现它的正确方法。
最佳答案
我建议采用以下方法。定义一个 private
函数模板称为 implementation
处理一般情况,重载(不 专门化)implementation
在 T=char*
时处理特定情况.然后从fun2()
, 调用 implementation
传递第三个参数,如下所示。正确的implementation
将根据模板参数选择 T
:
template<class T>
class A
{
template<typename U> struct selector{};
public :
void fun1(T val);
void fun2(T val1, T val2)
{
//forward the call
//a correct function will be selected automatically based on T
implementation(val1, val2, selector<T>());
}
private:
template<typename U>
void implementation(T & val1, T & val2, const selector<U> &)
{
//general case!
}
void implementation(T & val1, T & val2, const selector<char*> &)
{
//specific case when T = char*
}
};
selector<T>
类型的第三个参数(或 selector<char*>
)有助于选择正确的实现。
关于C++ 模板 : Partial template Function Specialization in template class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7791579/