I keep getting Link errors when trying to run my code. I have 4 LNK2019 Errors saying that there is "unresolved external symbol". So I assume at run-time the compiler cannot find my function definitions?
*UPDATE* I just did some more research and it appears that placing the function template definitions in the .h file fixes this problem. I just tried this in Visual Studio and can confirm that it fixed my issue. Is there any easy way around this issue so that I can have a .h file and .cpp file separately for a class template declaration and its function template implementations?
Here is the main .cpp file that I use to drive my program.
When I use the a non class template object like the list that I created, I don't have any problems. Only when using a class template do I get the link errors.
Example... this code below will compile just fine.
Is there any easy way around this issue so that I can have a .h file and .cpp file separately for a class template declaration and its function template implementations?
The compiler has to know the implementation code at compile time so it can instantiate the template. To separate the declaration from the code, put the code in a DLLTemplate.i and add #include "DLLTemplate.i" at the bottom of DLLTemplate.h.
> Is there any easy way around this issue so that I can have a .h file and .cpp file separately
> for a class template declaration and its function template implementations?
Yes, provided that you know before hand all the template arguments for which the template needs to be instantiated in the program.
An explicit instantiation declaration (an extern template) skips implicit instantiation step: the code that would otherwise cause an implicit instantiation instead uses the explicit instantiation definition provided elsewhere (resulting in link errors if no such instantiation exists). This can be used to reduce compilation times by explicitly declaring a template instantiation in all but one of the source files using it, and explicitly defining it in the remaining file.
As @dhayden said you can put the code in a #include "DLLTemplate.i" and include it at the buttom of the .h file or you could do it as a .cpp that it included at the end of a .h although both should generally be avoided (perfectly you should never include a .cpp in a .h file), but as an example:
templated_code.h:
--------------------
1 2 3 4 5 6 7 8
#ifndef TEMPLATED_CODE_H
#define TEMPLATED_CODE_H
//your class declaration with its template goes here
#include "templated_code.cpp"
#endif
templated_code.cpp:
----------------------
1 2 3
#include templated_code.h
//implementation goes here
OR you have another option:
in your .cpp file simply add at the end of the file: templateclass DLLTemplate<double>;
however it will only work when you make a double list, if you would want to use an int list you should add: templateclass DLLTemplate<int>;
to the end of the file (just change to the type you want to use insode of the <>).