0

I'm trying to create data structure for sorting data that will firstly receive any kind of object, i.e. int, string or MyCustomObject and then perform other tasks.

// heap.h
template <typename T>
class Heap{
public:
    Heap();
    ~Heap();    
}


//heap.cpp
template <typename T>
Heap<T>::Heap(){}

template <typename T>
Heap<T>::~Heap(){}

...

It turns out that from the very beginning when I try to run Heap<int> test it shows that classic message undefined reference to Heap<int>::Heap(). I found out that one workaround is to add template <typename int> at the end of the code.

However, if I try to do it with std::vector I'm pretty sure I can run std::vector<MyCustomObject> test which uses templates even without adding that line template<typename MyCustomObject> beforehand.

I want to know:

  1. How would I perform this same behavior in my data structure of receiving "unknown" types?
  2. Why std::vector implementation works whereas mine don't? What's missing?
testing_22
  • 2,340
  • 1
  • 12
  • 28

1 Answers1

1

To remove the undefined reference to Heap<int>::Heap() error you have to put the definition into the header file, too. Yes, that may seem strange, but that is the usual approach with templates:

heap.hpp:

template <typename T>
class Heap{
public:
    Heap();
    ~Heap();
};

template <typename T>
Heap<T>::Heap(){}

template <typename T>
Heap<T>::~Heap(){}

main.cpp:

#include "heap.hpp"

int main()
{
  Heap<int> test_with_int;
  Heap<double> test_with_double;
  return 0;
}
Striezel
  • 3,693
  • 7
  • 23
  • 37
  • C++20 is adding modules. But you need to find a C++20 conforming compiler – Basile Starynkevitch May 02 '21 at 15:00
  • What do you mean by that @BasileStarynkevitch? – testing_22 May 02 '21 at 15:07
  • 1
    As far as I known. C++20 has yet to see widespread adoption by major compilers. Even the newest GCC and Clang compilers only provide partial support for C++20 so far. – Striezel May 02 '21 at 15:12
  • @testing_22: [this webpage](https://en.cppreference.com/w/cpp/language/modules) explains what C++20 modules are. [this wikipage](https://gcc.gnu.org/wiki/cxx-modules) explains what [GCC](http://gcc.gnu.org/) has implemented, you need to use a very recent [GCC](http://gcc.gnu.org/) compiler in 2021 – Basile Starynkevitch May 02 '21 at 16:13
  • Perhaps you could be interested by the [RefPerSys](http://refpersys.org/) project. Then email me to `basile@starynkevitch.net` – Basile Starynkevitch May 02 '21 at 17:14