Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing std::tr1 into std - is it legal? Does it improve portability?

I have C++03 code that looks like this:

#include <boost/tr1/unordered_map.hpp>
...
std::tr1::unordered_map<std::string, int> mystuff;
...

I started to wonder that i would suffer later if/when i convert my code to C++11, which (i guess) doesn't have std::tr1::unordered_map but has std::unordered_map instead. So i came up with the following hack:

namespace std
{
    using namespace ::std::tr1;
}
...
std::unordered_map<std::string, int> mystuff; // no tr1 now!
...

Is it legal (maybe importing stuff into std is forbidden)? Will it make it easier to port/interoperate with C++11 code?

like image 621
anatolyg Avatar asked May 24 '12 10:05

anatolyg


Video Answer


1 Answers

You should not touch the std namespace: even if it works now, it can cause severe headaches later (with a new version of the compiler, on a different compiler, etc).

Update: Quote from the standard (C++ 2003, Section 17.4.3.1 "Reserved names") (found here):

It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces within namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined type of external linkage and unless the specialization meets the standard library requirements for the original template. [emphasis mine]

like image 114
Attila Avatar answered Oct 09 '22 22:10

Attila