Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STLPORT: What does namespace std{} mean?

Tags:

c++

namespaces

In the stlport library, I saw this code:

namespace std { }
namespace __std_alias = std;

1. Are they trying to nullify the standard std namespace in the first line?
2. Why in the world would they use a longer alias name in place of the original name?

like image 221
Nav Avatar asked Feb 28 '12 13:02

Nav


3 Answers

It is rather annoying to get a compiler error that there is no such namespace as std... What is the compiler thinking? Of course it exists!

Well yes it does, but as with library features, it has to be declared first. That is what the first line is doing.

With the renaming of __std_alias it allows them to give a new alias to a namespace. You may decide to do this in your own code someday.

Perhaps you want to use shared_ptr in your code but do not want to dedicate your code to using namespace boost or std. So you can create an alias, and "point" it at either boost or std. Same with other features that are in boost libraries that later became standard.

This does not tie you to using this namespace for everything as you can have more than one alias, and you can have more than one pointing to the same real namespace.

Let's say we want to call our smart pointer library sml. We can do

namespace sml = boost; // or std

in one place in the code and #include <boost/shared_ptr.hpp> from that point in the code (same header).

Everywhere else in our code we use sml::shared_ptr. If we ever switch from boost to std, just change the one header, not all your code.

like image 22
CashCow Avatar answered Nov 09 '22 16:11

CashCow


You need the namespace "in scope" before you can declare an alias to it. The empty namespace std {} informs the compiler that the namespace exists. Then they can create an alias to it.

There are reasons for creating aliases besides creating a shortcut. For example, you can define a macro to "rename" the namespace -- consider the effect of #define std STLPORT_std. Having a alias allows you to access the original namespace provided that you play the correct ordering games with header files.

like image 77
D.Shawley Avatar answered Nov 09 '22 15:11

D.Shawley


  1. No, that just makes sure the namespace's name is available in the current scope. You can open and close namespaces at any point, without affecting the contents of the namespace.

  2. I would guess, so they could easily change their library implementation to be in a namespace other than ::std (by changing __std_alias to alias something else). This would be useful, for example, if you want to test two implementations alongside each other.

like image 27
Mike Seymour Avatar answered Nov 09 '22 15:11

Mike Seymour