C ++子类专门化模板超类

时间:2018-06-01 21:34:38

标签: c++ templates

我想要一个抽象的通用超类,它有多个子类,专门用于特定类型的超类。例如:

base.h:

template <class T>
class Base {
 public:
  Base();
  void do_twice(const T& t);
  virtual void do_once(const T& t);
  virtual ~Base();
};

base.cc:

#include "base.h"

template <class T>
Base<T>::Base() {}

template <class T>
void Base<T>::do_twice(const T& t) {
  do_once(t);
  do_once(t);
}

template <class T>
Base<T>::~Base() {}

derived.h:

#include "base.h"

class Derived : public Base<int> {
 public:
  Derived();
  void do_once(const int& n) override;
  ~Derived();
};

derived.cc:

#include "derived.h"

Derived::Derived() : Base<int>() {}

void Derived::do_once(const int& n) {
  LOG(INFO) << "Derived: " << n;
}

Derived::~Derived() {}

这一切都是编译。但是在通话现场:

Derived d;
d.do_twice(0);

我收到编译错误:

main.cc:9: error: undefined reference to 'Base<int>::do_twice(int const&)'
derived.cc:3: error: undefined reference to 'Base<int>::Base()'
derived.cc:9: error: undefined reference to 'Base<int>::~Base()'

我可能误解了一些事情,因为我是C ++模板的新手,但不知道是什么。我怎样才能让这种东西起作用?或者对于这种类型的模式还有另一种更合适的方法吗?

0 个答案:

没有答案