在C++范型编程中如何只特化类的一个成员函数(一)

2014-11-24 08:06:43 · 作者: · 浏览: 0
我们知道在C++模板 编程中如果我们特化或是偏特化某个模板类, 我们需要重写整个模板类中的所有函数, 但是这些代码通常是非常相似的, 甚至在某些情况下可能只有一两个函数会不一样,其他函数都是一样的。在这种情况下,同时存在多份相同的代码,对我们维护这些代码是非常不利的, 我们最好只需要特化其中不一样的那个函数。
比如下面这个模板类:
template
struct Base
{
//other function
//....
void Func(){ cout << "primary function" << endl; }
};
void test1()
{
Base a;
a.Func();
Base b;
b.Func();
}
int main()
{
test1();
}
只有当B等于16时, Func这个函数需要特化, 但是其他函数无论什么情况下都是一样的。
下面是我们的一些可能解决方案:
方法1:
template
struct Base
{
//other function
//....
void Func(){ cout << "specialization function" << endl; }
};
点评:通过偏特化实现,需要重写所有的类成员方法。
方法2:
template
struct Base
{
//other function
//....
void Func()
{
if(B == 16)
{
cout << "primary function" << endl;
}
else
{
cout << "specialization function" << endl;
}
}
};
点评: 通过运行时判断, 容易理解,但是相对低效。
方法3:
template
struct Base
{
//other function
//....
void Func()
{
#if B!=16
cout << "primary function" << endl;
#else
cout << "specialization function" << endl;
#endif
}
};
点评: 试图通过预编译来实现,但是这个方法是错误的。C++模板编译包括预编译,语法检查,模板实例化等阶段,在预编译阶段模板参数都还没有实例化呢。
方法4:
template
struct Base
{
//other function
//....
template
struct FuncObj
{
void operator()()
{
cout<<"primary function"<
}
};
template<>
struct FuncObj<16>
{
void operator()()
{
cout<<"specialization function"<
}
};
FuncObj
Func;
};
点评: 通过成员类以防函数的形式特化, 增加了类成员变量。
方法5:
template
struct Base
{
//other function
//....
template
void FuncImpl()
{
cout<<"primary function"<
}
template<>
void FuncImpl<16>()
{
cout<<"specialization function"<
}
void Func()
{
FuncImpl();
}
};
点评:通过类成员模板函数特化来实现。
方法6:
template
struct Base
{
//other function
//....
template
class Int2Type
{
enum { value = N };
};
template
void FuncImpl(const Int2Type)
{
cout<<"primary function"<
}
void FuncImpl(const Int2Type<16>)
{
cout<<"specialization function"<
}
void Func()
{
FuncImpl(Int2Type());
}
};
点评: 通过将int根据值的不同转成不同的类型,然后通过函数重载实现。
方法7:
namespace
{
template struct conditional { typedef T type; };
template struct conditional {typedef U type; };
}
template
struct Base
{
//other function
//....
void Func ()
{
typedef typename ::conditional::type type;
Func_impl(type());
}
private:
struct primary_t { };
struct spec_t { };
void Func_impl (primary_t) { std::cout << "primary function" << std::endl; }
void Func_impl (spec_t ) { std::cout << "specialization function" << std::endl; }
};
点评: 和方法6类似,通过函数重载实现
方法8:
namespace
{
template struct enable_if { typedef T type; };
template struct enable_if {};
}
template
struct Base
{
//other function
//....
template
typename ::enable_if<16!=N>::type
FuncImpl () { std::cout << "primary function" << std::endl; }
template
typename ::enable_if<16==N>::type
FuncImpl () { std::cout << "specialization function" << std::endl; }
void Func() {
FuncImpl();
}
};
点评:通过enable_if, 利用SFINAE实现。
我们可以看到根据编译时模板参数int值的不同,我们重写模板类的