It is not possible to write an implementation of a template class in a separate cpp file and compile. All ways to do this, if anyone claims to, are workarounds that mimic the use of a separate cpp file, but in practice, if you intend to write a template class library and distribute it using header and lib files to hide the implementation, this is simply not possible.
To find out why, let's take a look at the compilation process. Header files are never compiled. They are only pre-processed. Then the pre-processed code is grouped with the cpp file, which is actually compiled. Now, if the compiler needs to create the appropriate memory layout for the object, it needs to know the data type of the template class.
In fact, it should be understood that the template class is not a class at all, but a template for a class whose declaration and definition is generated by the compiler at compile time after receiving information about the data type from the argument. Until a memory layout can be created, instructions for defining a method cannot be generated. Remember that the first argument to a class method is the 'this' operator. All methods of the class are converted to separate methods with the name mangling and the first parameter as the object on which it works. The argument to 'this', which actually indicates the size of the object that closes the template class, is not accessible to the compiler unless the user creates an object with a valid type argument. In this case, if you put the method definitions in a separate cpp file and try to compile it, the file object itself will not be generated with class information. Compilation will not fail, it will generate an object file, but it will not generate code for the template class in the object file. It is for this reason that the linker cannot find characters in object files, and the assembly failed.
Now, what is the alternative to hide important implementation details? As we all know, the main goal of separating the interface from the implementation is to hide the implementation details in binary form. Here you must separate data structures and algorithms. Your template classes should only represent data structures, not algorithms. This allows you to hide more important implementation details in separate class libraries without templates, classes within which template classes will work, or simply use them to store data. The template class will actually contain less code for assigning, receiving, and setting data. The rest of the work will be done by classes of algorithms.
I hope this discussion is helpful.
Sharjith N. Jan 26 '10 at 23:52 2010-01-26 23:52
source share