简体   繁体   English

将整个C ++ STL代码包含在.h而不是.cpp / .c文件中的原因是什么?

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

I just downloaded the STL source code and I noticed all the definition for the STL template classes are included in the .h file. 我刚刚下载了STL源代码,我注意到STL模板类的所有定义都包含在.h文件中。 The actual source code for the function definition is in the .h file rather than .cpp/.c file. 函数定义的实际源代码位于.h文件而不是.cpp / .c文件中。 What is the reason for this? 这是什么原因?

http://www.sgi.com/tech/stl/download.html 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 这是一篇简短而又(我认为)有关它的信息性文章: 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. 我最初说标准不需要它,但是看看C ++ 03中“export”的定义,我没有看到任何迹象表明它是可选的。 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. 这允许一些内联,这解释了为什么有时候使用模板化的东西(比如std :: sort)比普通的C工作得更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM