Home > Backend Development > C++ > Why Do I Get 'Undefined Reference to' Errors for Template Class Constructors, and How Can I Fix Them?

Why Do I Get 'Undefined Reference to' Errors for Template Class Constructors, and How Can I Fix Them?

Susan Sarandon
Release: 2024-12-12 19:58:10
Original
733 people have browsed it

Why Do I Get

"Undefined Reference to" Template Class Constructor [Duplicate]

The compiler error "undefined reference to..." for template class constructors signifies a lack of explicit instantiation instructions for the specific template classes used in the program. This issue arises because the compiler doesn't automatically compile template code until it's explicitly required.

Solution 1: Explicit Template Instantiation

Append explicit template instantiation statements to the end of the implementation file (cola.cpp in this case):

template class cola<float>;
template class cola<string>;
Copy after login

Additionally, include the following lines in nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std::string>;
Copy after login

This forces the compiler to compile the required template classes.

Solution 2: Include Implementation in Header File

Move the implementation code from cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h, respectively. This ensures the availability of function definitions in all translation units using the template classes.

Pros and Cons of Each Solution:

  • Solution 1:

    • Pro: More efficient as it only compiles the necessary template instances.
    • Con: Requires manual instantiation for each desired template class.
  • Solution 2:

    • Pro: More convenient and flexible, as it allows for future template class instantiations.
    • Con: Potentially slower compilation due to duplicate code generation for each translation unit.

Other Typos in the Code:

  • Mismatched pointer syntax in the cola.h declaration:
nodo_colaypila<T><T>* ult, pri;
Copy after login

should be:

nodo_colaypila<T>* ult, *pri;
Copy after login
  • Missing #endif at the end of nodo_colaypila.h.
  • Default parameter for nodo_colaypila constructor should be defined in the header file, not the implementation file.

The above is the detailed content of Why Do I Get 'Undefined Reference to' Errors for Template Class Constructors, and How Can I Fix Them?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template