2

I have a Hashmap Class in the header

template <typename K, typename M, typename H = std::hash<K>>
class HashMap {
public: 
template <class Iterator>
    HashMap(const Iterator& begin, const Iterator& end);
};

How do I declare this in the cpp file?

I tried:

template <class <typename K, typename M, typename H> Iterator>
HashMap<K, M, H>::HashMap(const Iterator& begin, const Iterator& end)

It does not work. Thanks.

cigien
  • 57,834
  • 11
  • 73
  • 112
Lucas Lu
  • 31
  • 3
  • One note: if you put the definition of the constructor into a separate file (.cpp while the template class is defined in the .h file) you would experience problems with linking the instantiations. – Dmitry Kuzminov Jun 16 '20 at 01:17
  • @JerryJeremiah, your caption is confusing. There are alternative solutions. – Dmitry Kuzminov Jun 16 '20 at 01:23
  • @DmitryKuzminov Sorry - my caption *is* the title of that other question. – Jerry Jeremiah Jun 16 '20 at 01:28
  • The answer for this question might be useful: "Why can templates only be implemented in the header file?" https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file And also this one: "Why the .cpp is not accessible by the compiler when instanciated a template class?" https://stackoverflow.com/questions/20838845/why-the-cpp-is-not-accessible-by-the-compiler-when-instanciated-a-template-clas – Jerry Jeremiah Jun 16 '20 at 01:29

1 Answers1

4

You need separate templates for the class and the constructor, like this:

template <typename K, typename M, typename H>
  template <class Iterator>
    HashMap<K,M,H>::HashMap(const Iterator& begin, const Iterator& end) {
 // ...
}

Note that the out of line definition of the constructor can't specify the default template parameters.

Also, your question says you want to put this in the .cpp file, but you shouldn't do that. Templates should always be in header files.

cigien
  • 57,834
  • 11
  • 73
  • 112