Inheriting from a virtual template class in C ++

How to inherit from a virtual template class in this code:

// test.h
class Base {
 public:
  virtual std::string Foo() = 0;
  virtual std::string Bar() = 0;
};

template <typename T>
class Derived : public Base {
 public:
  Derived(const T& data) : data_(data) { }

  virtual std::string Foo();
  virtual std::string Bar();

  T data() {
    return data_;
  }

 private:
  T data_;
};


typedef Derived<std::string> DStr;
typedef Derived<int> DInt;

// test.cpp
template<typename T>
std::string Derived<T>::Foo() { ... }
template<typename T>
std::string Derived<T>::Bar() { ... }

When I try to use DStr or DInt, the linker complains that there are unresolved external characters that are Derived<std::string>::Foo()both Derived<std::string>::Bar()and the same for Derived<int>.

Am I missing something in my code?

EDIT: Thanks to everyone. Now it is pretty clear.

+3
source share
3 answers

You need to define template<typename T> std::string Derived<T>::Foo() { ... }and template<typename T> std::string Derived<T>::Bar() { ... }in the header file. When the compiler compiles test.cpp, it does not know all the possible values Tthat can be used in other parts of the program.

, , , .cpp, . , , .

, "" , . , . .

. , T, , .

+6

, - .

inline , , .

, , , , .

+6

. : (, Comeau) , , - .

Even with Como, you have to use a keyword exportfor everything to work correctly. Since they are the only ones that realize export, the chances are pretty good, that you don't care.

+3
source

Source: https://habr.com/ru/post/1725649/


All Articles