Undefined Reference to Template Class Constructor
In this C code, the compiler generates the error "undefined reference to cola(float)::cola()". This error occurs because the compiler cannot find the implementation of the constructor for the template class cola.
Answer 1: Explicit Template Instantiation
One solution is to explicitly instantiate the template class cola at the end of cola.cpp, forcing it to compile the concrete instantiations.
template class cola<float>; template class cola<string>;
Answer 2: Header File Inclusion
Alternatively, the implementation of the template class can be moved to the header file cola.h. This ensures that the implementation is available to all translation units that include the header file.
Reason for Header File Inclusion
Putting the implementation in the header file avoids the need for explicit instantiation. It guarantees that the template class and its member functions are available to every translation unit that includes the header file. This approach is commonly used for template classes that are widely used throughout the codebase.
Additional Notes:
The above is the detailed content of Why Does My C Code Produce an 'Undefined Reference to Template Class Constructor' Error?. For more information, please follow other related articles on the PHP Chinese website!