Splitting templated C++ classes into .hpp/.cpp files--is it possible?

前端 未结 16 1216
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 17:27

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         


        
16条回答
  •  一整个雨季
    2020-11-22 17:45

    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
    }
    

提交回复
热议问题