What is the reason for the entire C++ STL code to

2019-06-25 13:24发布

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

2条回答
霸刀☆藐视天下
2楼-- · 2019-06-25 13:33

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.

查看更多
来,给爷笑一个
3楼-- · 2019-06-25 13:39

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.

查看更多
登录 后发表回答