What is the reason that all C ++ STL code will be included in .h files rather than .cpp / .c?

I just downloaded the STL source code and I noticed that the entire definition of STL template templates is included in the .h file. The actual source code for the function definition is in the .h file, not in the .cpp / .c file. What is the reason for this?

http://www.sgi.com/tech/stl/download.html

+4
source share
2 answers

Because very few compilers implement template bindings. It's difficult.

Here is a short but (I think) informative article about this: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=53

I say "I think" because it is really not that I am very familiar with the fact that it is not widely implemented. I initially said that the standard does not require this, but looking at the definition of "export" in C ++ 03, I see no indication that it is optional. Perhaps this is just a bad standard.

+16
source

Think of templates as code generation. If you do not know in advance which template you will use, you will not be able to compile. Therefore, you need to save the implementation in the header.

This allows you to make some investments, and this explains why sometimes using templates (like std :: sort) works faster than in regular C.

+1
source

All Articles