1

So I have this code:

//HashTable.hpp:

 template <class dataType>
    class HashTable
    {
    public:

    //Something
    public:
                                                        HashTable();
                                                        HashTable(unsigned int & tableSize);

//HashTable.cpp:

#include "HashTable.hpp"


template <class dataType>
HashTable<dataType>::HashTable()
{

}

Now, in main() body I just instantiate an object HashTable<int> hTable. When compiling with g++, I get this error :

`EntryPoint.cpp:(.text+0x1f): undefined reference to `HashTable<int>::HashTable()  '
 collect2: error: ld returned 1 exit status`

What causes this problem? I recall I've hit this wall a few months ago when doing some templated data structures, but I just quick-fixed it in an error-prone way by including the file.cpp in the entry point's .cpp file. How can this be solved in a clean way? I've tried creating the object files and linking them individually, but I just get the same error. This specific problem frustrated me in such a way(lost > 10 hours researching it) that I've just stopped doing templates. I do not want to force the functions as inlines, as that's a very messy way of solving this. Also, I would avoid including HashTable.cpp instead of HashTable.hpp, as this overrides the concept of header files. I want my class to be as abstract as possible, so I can use it with all data types that I will later create.

Also, I do know that this can be solved by explicit instatiation, but I want to be able to use it with any types without having to "bloat" the code.

curious student
  • 322
  • 2
  • 11
  • The implementation of templates must be visible for any other source which shall use it. (It's not like classes.) Imagine templates as "construction plan". The actual classes are built (on demand) during compile itself. So move the implementations of methods from //HashTable.cpp to //HashTable.hpp and it should work. – Scheff's Cat Mar 04 '17 at 07:13
  • Ok, but why is this considered a solution? Is this not almost the same as forcing inline functions? – curious student Mar 04 '17 at 07:22
  • They look like inline functions. Whether the compiler inlines a function or not it decides by itself (even if you explicitly use keyword `inline`). IMHO this is OK because modern compilers does know better than the average C++ programmer where it makes sense. – Scheff's Cat Mar 04 '17 at 07:27
  • In your case, it will work even if you simply copy/paste the code of .cpp to .hpp (of course except the `#include`). (And don't forget to exclude .cpp from build.) This is how we did in the past because I didn't like the "look like inline". (Meanwhile I'm able to manage it...) – Scheff's Cat Mar 04 '17 at 07:29

0 Answers0