c++ - 大型模板类样板代码

标签 c++ templates dry

我有一个包含多个方法等的大型模板类。

大多数方法不使用模板参数 - 只有少数方法使用模板参数。

有没有办法尽量减少样板代码?

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/

相关文章:

javascript - 如何在 Backbone JS 中将多个路由定向到同一个方法?

c++ - 调试断言失败 OpenCv is_block_type_valid(header->_block_use)

c++ - 如何声明一个常量的方法指针

c++ - 与函数指针、__cdecl 和模板的混淆

c++ - 两阶段查找 : is it possible to easily mix inheritence and templates

javascript - 如何在 JavaScript/CoffeeScript 中优雅地循环链式调用?

c++ - Pthread_create 在 C++ 中导致段错误

c++ - 将 cout 重定向到文件与直接在 linux 中写入文件

c++ - 重载运算符|对于固定大小的数组?

inheritance - Sublime Text 支持主题继承吗?