在C++泛型编程中如何只特化类的某个成员函数
作者:网络转载 发布时间:[ 2013/4/24 10:02:45 ] 推荐标签:
下面我们考虑另外一个需求,当模板类的某个参数是某种类型时,我们要求特化其中的一个成员函数:
template<typename T1, typename T2>
struct Base
{
//other function
//....
void Func(){ cout << "primary function" << endl; }
};
void test2()
{
Base<int, int> a;
a.Func();
Base<int, string> b;
b.Func();
}
int main()
{
test2();
}
要求上面的模板类如果T2 是string类型,我们要求对Func特殊重写,其他的成员函数无论什么情况实现都是一样的。
有了上面的那个例子的实现经验,对这个问题我们解决方便多了。
方法1:
template<typename T1, typename T2>
struct Base
{
//other function
//....
void Func()
{
if(typeid(std::string) == typeid(T2))
{
cout<<"specialization function"<<endl;
}
else
{
cout << "primary function" << endl;
}
}
};
点评:通过运行时类型识别(RTTI)实现,需要打开相关编译选项,并且低效。
方法2:
template<typename T1, typename T2>
struct Base
{
//other function
//....
template<typename T>
void FuncImpl()
{
cout << "primary function" << endl;
}
template<>
void FuncImpl<string>()
{
cout << "specialization function" << endl;
}
void Func()
{
FuncImpl<T2>();
}
};
点评:通过成员函数特化实现
方法3:
template<typename T1, typename T2>
struct Base
{
//other function
//....
template<typename T>
class Type2Type
{
typedef T type;
};
template<typename T>
void FunImpl(const Type2Type<T>)
{
cout << "primary function" << endl;
}
template<typename T>
void FunImpl(const Type2Type<string>)
{
cout << "specialization function" << endl;
}
void Func()
{
FunImpl<T2>(Type2Type<T2>());
}
};

sales@spasvo.com