Reputation: 3558
I have been looking for a way to separate template class declaration and definition. I have been recommended a solution that has include guards in both Header.h and Source.cpp and Header.h includes Source.cpp after #endif
of include guard.
I thought linker would complain about re-definition (multiple symbols?) of the template class but it somehow doesn't and why not?
Doesn't this lead to duplicate code in the binary result? Each time header is included in a source file, the definition of the same class is also included.
Upvotes: 2
Views: 435
Reputation: 5345
Symbols are not multiply defined because template functions are inline.
Including .h in .cpp file and then including .cpp file in .h file works fine because .h files have guards, so header file is not included 2 times.
Overall, it is not a good idea to use .cpp files for that, as it is very confusing, and in a nutshell is same as just including implementations in .h file. You can create separate .hpp file with _Impl.hpp index to store implementations.
Upvotes: 1
Reputation: 12415
You must include header guards also in implementation file. Don't use .cpp anyway, it's confusiing. I put declaration in header.h and implementation in header-inl.h, for example.
Upvotes: 0
Reputation: 96258
Upvotes: 1
Reputation: 7960
The object file created by compilation of each CPP file will contain duplications. Those duplications are removed by the linker.
Upvotes: 1
Reputation: 545588
For normal symbols, this would indeed lead to double definitions. However, templates are treated distinctly and as if they had internal linkage. Consequently, there’s no double definition.
However, it’s a patently bad idea to put the implementation into cpp
files – this will confuse lots of tool chains, which assume by convention that such files are to be compiled. Rename the files to ipp
– this is often used for such template implementation files.
Upvotes: 1