I just downloaded the STL source code and I noticed all the definition for the STL template classes are included in the .h file. The actual source code for the function definition is in the .h file rather than .cpp/.c file. What is the reason for this?
http://www.sgi.com/tech/stl/download.html
Because very few compilers implement linking of templates. It's hard.
Here's a brief but (I think) informative article about it: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=53
I say "I think" because it's really not something I'm very familiar with other than that it's widely unimplemented. I initially said the standard didn't require it, but looking at the definition of "export" in C++03, I don't see any indication that it's optional. Maybe it's just a failed standard.
Think of templates as code generation. If you don't know beforehand what template will be used with, you can't compile. So you need to keep the implementation in the header.
This allows some inlining and that explains why sometimes using templated stuff (like std::sort) works faster than in plain C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With