我有一个包含多个方法等的大型模板类。
大多数方法不使用模板参数 - 只有少数方法使用模板参数。
有没有办法尽量减少样板代码?
template <class T>
class Something{
void method1();
void method2();
void method3();
};
template <class T>
void Something<T>::method1(){
T::use();
}
template <class T>
void Something<T>::method2(){
// do not use T at all, does not call method1()
}
template <class T>
void Something<T>::method3(){
// do not use T at all, does not call method1()
}
任何我能避免的方式template <class T>
(在我的真实代码模板定义中要大得多)?
最佳答案
将非模板依赖的方法放在基类中。
class SomethingBase
{
protected:
void method2();
void method3();
};
template<typename T>
class Something
: SomethingBase
{
public:
void method1();
using SomethingBase::method2;
using SomethingBase::method3;
};
这不会改变类的功能,但比 Neil Kirk 的方法要麻烦一些,如果适用,应该首选这种方法。
如果基类的唯一功能是为派生类提供不太专业的功能,那么它的所有成员(包括构造函数)都应该受到保护
。
关于c++ - 大型模板类样板代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33268894/