Is there "magic" in the STL? [closed]

Let me start with explaining what I mean with "magic". I will use two examples from Java:

  1. Every class inherits (directly or indirectly) the Object class.
  2. Operator overloading is not supported by Java but the + operator is defined for String objects.

This means that it is impossible to make an implementation of the Object and String classes in pure(*) Java. Now this is what I mean with "magic": to make an implementation of these classes, you will need some special support from the compiler.

What I always liked about C++ is that, as far as I know, there is no such "magic" going on in the STL, i.e. it is possible to implement the STL in pure C++.

Now my question is: is this true? Or are there parts of the STL that cannot be implemented in pure C++ and need some "magic"/special compiler support?


(*) With "pure" I mean without using any class libraries.


Solution 1:

in other words, has anything been done to the compiler to allow for a 'special case' the STL needed to work?

No.

It was all implemented as 'pure' C++ code, using the magic of templates.

There has been some work done to compilers to improve the STL (I'm thinking about various optimisations) but otherwise, no, you could write the entire STL if you really wanted. Some people did - STLPort is an implementation that didn't have the backing of any compiler manufacturer.

Solution 2:

Like gbjbaanb correctly said, the STL can be implemented in plain C++, without relying on any kind of compiler "magic".

However, if you go digging in the STL source code for your compiler, you'll probably see code that either isn't standard, or which you're not supposed to write yourself.

The STL can be implemented entirely in standard C++, but that doesn't mean compiler writers aren't allowed to improve it occasionally, using compiler-specific extensions. For example, they might insert non-standard code that ensures better error messages, or perhaps works around some flaw in their compiler, or maybe enables special optimizations by using extra features of that specific compiler.

They also consistently use names that you're not allowed to use. For example, template parameters are typically named something like _Type, which, since it starts with an underscore followed by a capital letter, is reserved for the implementation. The standard library is allowed to use them, but you and I are not. So if you were going to write your own STL implementation, you would have to make some minor changes, but that's not because of any magic, just a way to avoid name clashes between the standard library and user code.