I am getting errors trying to compile a C++ template class which is split between a .hpp
and .cpp
file:
$ g++ -c -o main.o main.cpp
The problem is that a template doesn't generate an actual class, it's just a template telling the compiler how to generate a class. You need to generate a concrete class.
The easy and natural way is to put the methods in the header file. But there is another way.
In your .cpp file, if you have a reference to every template instantiation and method you require, the compiler will generate them there for use throughout your project.
new stack.cpp:
#include
#include "stack.hpp"
template stack::stack() {
std::cerr << "Hello, stack " << this << "!" << std::endl;
}
template stack::~stack() {
std::cerr << "Goodbye, stack " << this << "." << std::endl;
}
static void DummyFunc() {
static stack stack_int; // generates the constructor and destructor code
// ... any other method invocations need to go here to produce the method code
}