C++ template, linking error [duplicate]
Solution 1:
Template functions, including member functions, must be written entirely in the header files. This means that if you have a template class, its implementation must be entirely in a header file. This is because the compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template.
Solution 2:
Put both the template declaration and the template function definitions in the header file. Most C++ compilers do not easily support the separate compilation model for templates,
Solution 3:
If the definition of a templated function is not visible at the point where it is used (i.e. is not in the header or the same CPP file), you need to tell the compiler which instantiations to make.
Solution 4:
The problem you have here is that you have hidden the definition of the constructor in the .cpp file. This definition applies to all types T
, including T
as an int
that you use, but actually supplies no definitions whatsoever because its still only a declaration.
The linker cannot find the symbol Array<int>::Array()
.
Now, you can add a line like this:
Array<int> arr1;
to the end of your Array.cpp file and this makes the compiler instantiate the correct definition that the linker is looking for. However, this only supplies one definition, that of Array<int>
and no other.
This solution will work, until you need an Array
of a different template parameter, say, double
, at which point you would need to add:
Array<double> arr2;
to the end of your Array.cpp file - now you can see how this is unsustainable!
If you need C++ to work with any type that you might want in the future, now is the time to move the definition of the ctor (and presumably all the other member functions) up into the header (and delete the .cpp file as it won't have anything left in it).
Solution 5:
As mentioned above, in templates in C++ the process of new methods is executing by the compiler at compile time, the problem is that it needs to know all definition of thm during that time, so all class/function declaration must be ar h or hpp files.