Is it acceptable to add types to the std
namespace. For example, I want a TCHAR-friendly string, so is the following acceptable?
#include <string>
namespace std
{
typedef basic_string<TCHAR> tstring;
}
Or should I use my own namespace?
Is it acceptable to add types to the std
namespace. For example, I want a TCHAR-friendly string, so is the following acceptable?
#include <string>
namespace std
{
typedef basic_string<TCHAR> tstring;
}
Or should I use my own namespace?
You should use your own namespace as adding code to the standard library will only confuse the users that will look online for informations about that addition.
All that is in std should be only the standard library and nothing else.
No ... part of the point of a namespace is to prevent name collisions on upgrade.
If you add things to the std namespace, then your code might break with the next release of the library if they decide to add something with the same name.
Officially, the standard says that's "undefined behaviour", and all kinds of nasty things can happen.
In practice, it will work fine, but you still shouldn't do it. What does it buy you, other than confusing people that something is provided by the compiler?
Only specializations are allowed. So for example, you are allowed to specialize std::swap
for your type. And this of course must happen in namespace std::
. But your typedef isn't a specialization so that's causing undefined behavior.
I totally agree with other answers saying that you should put your types in your own namespace to avoid unfortunate name collisions.
However, I wanted to precise that sometimes, you can (and should !) add stuff in the std namespace. This is the case for template specializations of the std::swap method for example, which are used to provide a uniform way to swap objects. For more information on this matter, you can read about the non-throwing swap idiom.