开发者

What is the reason for the entire C++ STL code to be included in the .h rather than .cpp/.c files?

开发者 https://www.devze.com 2022-12-11 04:57 出处:网络
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 fil开发

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 fil开发者_高级运维e 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号