Home >Backend Development >C++ >Can Templated C Classes Be Split into .hpp and .cpp Files?

Can Templated C Classes Be Split into .hpp and .cpp Files?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-22 05:49:08962browse

Can Templated C   Classes Be Split into .hpp and .cpp Files?

Splitting Templated C Classes into .hpp/.cpp Files: Is It Possible?

Problem:

Attempting to split a templated C class into .hpp and .cpp files results in compilation errors due to undefined references to constructor and destructor symbols.

main.cpp:(.text+0xe): undefined reference to 'stack<int>::stack()'
main.cpp:(.text+0x1c): undefined reference to 'stack<int>::~stack()'

Code:

stack.hpp

#ifndef _STACK_HPP
#define _STACK_HPP

template <typename Type>
class stack {
    public:
            stack();
            ~stack();
};
#endif

stack.cpp

#include <iostream>
#include "stack.hpp"

template <typename Type> stack<Type>::stack() {
        std::cerr << "Hello, stack " << this << "!" << std::endl;
}

template <typename Type> stack<Type>::~stack() {
        std::cerr << "Goodbye, stack " << this << "." << std::endl;
}

main.cpp

#include "stack.hpp"

int main() {
    stack<int> s;

    return 0;
}

Answer:

It is not feasible to implement templated classes in a separate .cpp file and compile them. The implementation must be included in the .hpp file because the compiler requires knowledge of the data type when generating memory layout and method definitions for template classes. Attempting to compile the .cpp file independently will result in the following issues:

  • The object file will not be generated with the class information.
  • The linker will not find the symbols in the object files, and the build will fail.

Alternative Solution:

To hide implementation details, consider separating data structures and algorithms. Create templated classes to represent data structures, while non-templatized classes handle the algorithms and utilize the data structures. This enables the concealment of essential implementation details in separate libraries without relying on template classes.

The above is the detailed content of Can Templated C Classes Be Split into .hpp and .cpp Files?. 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