In C programming, template classes are often used to provide generic functionality that can be instantiated with different types. However, sometimes when instantiating a template class, you may encounter an "undefined reference to" error.
This error occurs when the compiler cannot find the implementation for the constructor of the template class. The compiler typically needs to see the implementation of the constructor in order to generate the code for the instantiated class.
In the provided code, the template class cola is defined in cola.h header file, but the implementation is in the cola.cpp file. When compiling the program, the compiler sees the template declaration in main.cpp and attempts to implicitly instantiate the cola class with float and string types.
However, since the compiler has not yet seen the implementation of the constructor in cola.cpp, it cannot generate the code for these instantiated classes, resulting in the "undefined reference to" error.
There are two approaches to resolve this issue:
Add explicit template instantiations at the end of the cola.cpp file:
template class cola<float>; template class cola<string>;
This explicitly instructs the compiler to generate code for the cola template class with the specified types.
Move the implementation of the template class constructor and member functions into the header file (cola.h and nodo_colaypila.h).
This ensures that the compiler sees the implementation when it instantiates the template class, eliminating the need for explicit instantiation.
In Approach 1, explicit instantiation is done at the end of the translation unit (a single compiled file). This means that all code in that file must be compiled before the instantiation.
In Approach 2, the implementation is in the header file, which is included in every translation unit that uses the template class. As a result, the implementation is available to the compiler regardless of the order of compilation.
Both approaches are valid solutions to the "undefined reference to" error with template classes. The choice depends on the specific needs of the project. Explicit instantiation is more flexible and allows for better control over which template specializations are generated. However, moving the implementation to header files is more common and provides more flexibility in using the template class.
The above is the detailed content of Why Do I Get an 'Undefined Reference to' Error with Template Class Constructors in C ?. For more information, please follow other related articles on the PHP Chinese website!