Home >Backend Development >C++ >Why Do I Get 'Undefined Reference to Template Class Constructor' and How Can I Fix It?

Why Do I Get 'Undefined Reference to Template Class Constructor' and How Can I Fix It?

DDD
DDDOriginal
2024-12-09 19:57:15490browse

Why Do I Get

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn