0

When compiling my program, I am getting a link error LINK2019. The common error is that a function was declared but not defined which is not the case here. For example I have the class below that is defined in the header file dict.h

template<typename key, typename elem>
class Slist{
public:
    list<KV_pair<key, elem>> *data;

    Slist(int size);
    ~Slist();

    void insert(KV_pair<key, elem> &kv);
    elem &operator[](key k_val);
};

And I have defined the members as so in a separate dict.cpp file

template<typename key, typename elem>
Slist<key, elem>::Slist(int size) {
    data = new list<KV_pair<key, elem>>(size);
}

template<typename key, typename elem>
Slist<key, elem>::~Slist() {


}

template<typename key, typename elem>
void Slist<key, elem>::insert(KV_pair<key, elem> &kv){
    KV_pair<key, elem> *temp;
    for (data->movestart();data->r_len() > 0; data->next()) {
        temp = &data->get_val();
        if (temp->get_key() > kv.get_key()) {
            break;
        }
        data->insert(kv);
    }
}

If I put my main() in the dict.cpp file everything works, but when I try to put the main() in a separate file and #include "dict.h" I get the unresolved externals error. Although it is incorrect to do so, using #include "dict.cpp"after #include "dict.h" resolves the error. I have the dict.h file in the header files directory, and put both the main.cpp and dict.cpp in the source files directory/

Anandamide
  • 243
  • 1
  • 15
  • 2
    [Why Can templates only be in header](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Fantastic Mr Fox Oct 16 '15 at 20:51
  • 2
    Class declaration and defenition in template case must be in single file. – Mykola Oct 16 '15 at 20:52
  • Excellent, I was having a bit of a meltdown when this wouldn't work. c++ is definitely a bit of a minefeild of subtleties and pitfalls. – Anandamide Oct 16 '15 at 20:57
  • So the best solution in the link provided advises to make a .tpp file and include it at the end of the header. What directory should I place the .tpp file? – Anandamide Oct 16 '15 at 20:58
  • @Mykola: Not necessarily, see the question that Ben linked in his comment. Templates can be explicitly instantiated in a .cpp file. – Blastfurnace Oct 16 '15 at 21:01

1 Answers1

0

The compiler expands templated types (and functions) at the point they are used. This means that the compiler must be able to find their definition at the point they are used. For this reason all template definitions (not just declarations) must exist in the header, or a file included in the header.

gmbeard
  • 674
  • 6
  • 19