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

前端 未结 16 1212
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  -上瘾入骨i
    2020-11-22 17:49

    1) Remember the main reason to separate .h and .cpp files is to hide the class implementation as a separately-compiled Obj code that can be linked to the user’s code that included a .h of the class.

    2) Non-template classes have all variables concretely and specifically defined in .h and .cpp files. So the compiler will have the need information about all data types used in the class before compiling/translating  generating the object/machine code Template classes have no information about the specific data type before the user of the class instantiate an object passing the required data type:

            TClass myObj;
    

    3) Only after this instantiation, the complier generate the specific version of the template class to match the passed data type(s).

    4) Therefore, .cpp Can NOT be compiled separately without knowing the users specific data type. So it has to stay as source code within “.h” until the user specify the required data type then, it can be generated to a specific data type then compiled

提交回复
热议问题