If you write the declaration and implementation of a class template in two separate files, the error LNK2019: unresolved external symbol will appear at build time.
The workarounds are:
- The first way is to put the declaration and definition of member functions in the class template in the definition of the class (. h file), do not separate the line.
- The second method, in the main file (main file), contains both the declaration file (interface file) (. h file) of the class template, and also the implementation file (. cpp file) of the class template.
- The third method, in the definition of the class (. h file), contains the implementation file (. cpp file) of the class template.
The reason is that template classes and template functions are instantiated when they are used. When a template is used, the compiler needs all the implementation code of the function to build the correct function with the appropriate type (template parameters). However, if the function is implemented in a separate source file, the files are not visible and thus error occurs.
The following is an excerpt from StackOverflow's answer:
Anyway, the reason your code is failing are, when instantiating a template, the compiler creates a new class with the Given template argument. For example:
Template<typename t>struct foo{ T bar; void dosomething (T param) {/** / }}; // somewhere in a. cpp foo<int> F;
When reading this line, the compiler would create a new class (Let's call it Fooint), which are equivalent to the following:
struct fooint{ int bar; void dosomething (int param) {/** / }}
Consequently, the compiler needs to has access to the implementation of the methods, to instantiate them with the Templat e argument (in this case int). If these implementations were not in the header, they wouldn ' t is accessible, and therefore the compiler wouldn ' t be able To instantiate the template.
Reference:
CSDN: template class error LNK2019: unresolved external symbol
Stackoverflow:why can templates only is implemented in the header file?
Template class Error LNK2019: unresolved external symbol