C ++ template class header file

C ++ template class header file

This is my third in a blog on header files, I did not think I stepped on a giant pit.

We all know that to declare a class member in the header file, implemented in the source file.

But today write data structures work, in the header file (Stack.h) defines a template class stack in the source file (Stack.cpp) to achieve the corresponding functions. But the compiler, but life and death, how to change how could not pass.

It was found that the template class not only in the header file declarations, must be implemented in the header file.

It is impossible to just write a template class in a separate cpp files and compile the achieve. If someone says you can, then it is surely a way to mimic a separate cpp files. In fact, if you plan to write a template library and header files to import, and hide the implementation, it was impossible.

why?

Because the header file is never compiled, only pretreatment. Then finished pre-code corresponding to the actual compilation cpp files are merged. C ++ in space occupied by each object, it is compile time is determined. When the template class does not have the type of incoming data, the compiler can not know the size of objects in the space occupied by the class template.

Therefore, during the pre-finished header and source files of the binding, the compiler is completely unaware of the source file space template class, but it needs to compile the source files. So it can not compile it.

So remember, when the only real class template is used, the compiler know what type of template is passed, how much space needs to be allocated.

Template class implementation, if out of specific data types, it is absolutely impossible to separate compilation. Not to mention the declarations in header files, this method undesirable realized in the source file.

So realize all of template class must write in the header files!

Of course, it can now be declared within the class header file, achieved outside the braces.

Unless you want in the main file, play #include "xxxx.cpp" magical operation.

Guess you like

Origin www.cnblogs.com/scyq/p/12507105.html