Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

but what can you do...

    using namespace std;

    map<string, vector<string>> foo;


I used to do this. But then I realized I would be importing all symbols from std into my code. Including ones that might get defined in the future (similar to python's 'from foo import *'), which might conflict with some of my own symbols.

Hence, I now implicitly import each symbol I need with something like 'using std::map;' (similar to python's 'from foo import bar, bar2').

I've found that the 'using' statement can be used even inside a function to restrict the importation to just a single function.

FYI.


That's good advice. But even when importing all of std, at least namespace collisions in C++ will result in some somewhat sane compiler error.

I not so fondly remember a day hunting down a cryptic C compiler error coming from some header that had

      #define F1 ...,
replacing F1 in my file by some cryptic mess...


Interesting; I never thought of that analogy to Python. I've just had it drilled into my head from everything I've ever read about C++ that "using namespace std" is terrible, and I shouldn't use it.

Great advice. Thanks!


Except the analogy to Python lacks one critical point: C++ headers and Python imports do not work in nearly the same way. Do not EVER use a "using namespace <foo>" in a header file; any code that #include's such a header will pull this in.

In .cpp files it's ok (and almost required if you're using boost, unless you want boost::foo:bar::type everywhere). It still requires a bit of thought, though.


It's ugly to see shift operator here? :-)


Unless you're on C++11 you'll be required to shove a space in there to get it to compile anyway ;)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: