在C++泛型编程中如何只特化类的某个成员函数
作者:网络转载 发布时间:[ 2013/4/24 10:02:45 ] 推荐标签:
方法4:
template<typename T, unsigned B>
struct Base
{
//other function
//....
template<unsigned S>
struct FuncObj
{
void operator()()
{
cout<<"primary function"<<endl;
}
};
template<>
struct FuncObj<16>
{
void operator()()
{
cout<<"specialization function"<<endl;
}
};
FuncObj<B> Func;
};
点评:通过成员类以防函数的形式特化,增加了类成员变量。
方法5:
template<typename T, unsigned B>
struct Base
{
//other function
//....
template<unsigned N>
void FuncImpl()
{
cout<<"primary function"<<endl;
}
template<>
void FuncImpl<16>()
{
cout<<"specialization function"<<endl;
}
void Func()
{
FuncImpl<B>();
}
};
点评:通过类成员模板函数特化来实现。
方法6:
template<typename T, unsigned B>
struct Base
{
//other function
//....
template<unsigned N>
class Int2Type
{
enum { value = N };
};
template<unsigned V>
void FuncImpl(const Int2Type<V>)
{
cout<<"primary function"<<endl;
}
void FuncImpl(const Int2Type<16>)
{
cout<<"specialization function"<<endl;
}
void Func()
{
FuncImpl(Int2Type<B>());
}
};
点评:通过将int根据值的不同转成不同的类型,然后通过函数重载实现。

sales@spasvo.com