Template Link Error LNK2019 Can be avoided

I have seen this Link Error when using templates with Microsoft Visual C++ on many occasions. This is the error:

Error LNK2019: unresolved external symbol "public: ..."

Everyone seems to be advising that all template class code needs to be accumulated in the header file. Well as it turns out, it doesn't. You can have separate header (.h) and definition (.cpp) files for your template class and and manage to avoid these unusual LINK Errors (LNK 2019).

Here is what you need to add to the top of your definition (.cpp) file in order to avoid this error:

template class Your_Class_Name<needed_type>;

You have to put one line per needed type. Otherwise, if you need to use Your_Class_Name for int and float, you need to put the following two lines:

template class Your_Class_Name<int>;
template class Your_Class_Name<float>;

That is all there is to it!










We know, It has previously been discussed.
It is called explicit instantiation.
... or template pre-instantiation.
Topic archived. No new replies allowed.