Home >Backend Development >C++ >Why Do I Get 'Undefined Reference to Template Class Constructor' and How Can I Fix It?
Why "Undefined Reference to Template Class Constructor"?
A template class defines a blueprint for creating classes with different types. To use a template class, you need to instantiate it with a specific type. In your case, you have two template classes: nodo_colaypila and cola.
However, the compiler needs to know about the constructors of the instantiated classes before compiling the code. Since you are not explicitly instantiating the template classes with specific types, the compiler doesn't know which constructors to include.
Two Solutions:
There are two ways to resolve this issue:
Solution 1: Explicit Template Instantiation
Add explicit template instantiations at the end of cola.cpp:
template class cola<float>; template class cola<string>;
Ensure that all template definitions are in one translation unit (.cpp file) and the explicit instantiations are at the end of the file.
Solution 2: Move Code to Header Files
Move the code implementing the member functions from cola.cpp and nodo_colaypila.cpp to the corresponding header files .h. Doing so makes the function implementations available to all translation units that include these headers.
Summary:
The explicit template instantiation approach allows you to control the instantiation of specific types. The 'move-code-to-header-files' approach is commonly used and makes implementation available to all translation units. The choice depends on your specific needs and project requirements.
The above is the detailed content of Why Do I Get 'Undefined Reference to Template Class Constructor' and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!