Judeo
Judeo

Reputation: 43

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. 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

Upvotes: 4

Views: 387

Answers (2)

Tristram Gräbener
Tristram Gräbener

Reputation: 9711

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.

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279385

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.

Upvotes: 16

Related Questions