在C++泛型编程中如何只特化类的某个成员函数
作者:网络转载 发布时间:[ 2013/4/24 10:02:45 ] 推荐标签:
我们知道在C++模板编程中如果我们特化或是偏特化某个模板类, 我们需要重写整个模板类中的所有函数, 但是这些代码通常是非常相似的, 甚至在某些情况下可能只有一两个函数会不一样,其他函数都是一样的。在这种情况下,同时存在多份相同的代码,对我们维护这些代码是非常不利的, 我们好只需要特化其中不一样的那个函数。
比如下面这个模板类:
template<typename T, unsigned B>
struct Base
{
//other function
//....
void Func(){ cout << "primary function" << endl; }
};
void test1()
{
Base<int, 1> a;
a.Func();
Base<int, 16> b;
b.Func();
}
int main()
{
test1();
}
只有当B等于16时, Func这个函数需要特化, 但是其他函数无论什么情况下都是一样的。
下面是我们的一些可能解决方案:
方法1:
template<typename T>
struct Base<T, 16>
{
//other function
//....
void Func(){ cout << "specialization function" << endl; }
};
点评:通过偏特化实现,需要重写所有的类成员方法。
方法2:
template<typename T, unsigned B>
struct Base
{
//other function
//....
void Func()
{
if(B == 16)
{
cout << "primary function" << endl;
}
else
{
cout << "specialization function" << endl;
}
}
};
点评:通过运行时判断,容易理解,但是相对低效。
方法3:
template<typename T, unsigned B>
struct Base
{
//other function
//....
void Func()
{
#if B!=16
cout << "primary function" << endl;
#else
cout << "specialization function" << endl;
#endif
}
};
点评:试图通过预编译来实现,但是这个方法是错误的。C++模板编译包括预编译,语法检查,模板实例化等阶段,在预编译阶段模板参数都还没有实例化呢。

sales@spasvo.com