3

I understand that using namespace std; is problematic (e.g. from reading the answers to "Why is using namespace std considered bad practice?").

What are good alternatives to importing the standard namespace like that?

I'd like to know what I can do to improve my code.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Ricky Slayer
  • 41
  • 1
  • 2
  • Welcome to Stack Overflow! I've made an [edit] to your question to concentrate on the part for which I couldn't find an existing good answer. It's quite a drastic edit, but I think it makes a question that can be reopened and useful. – Toby Speight May 17 '17 at 17:11

2 Answers2

5

The main alternatives to bringing in everything from the std namespace into the global one with using namespace std; at global scope are:

  1. Only bring in the actual names you need. For example just bring in vector with using std::vector;

  2. Always use explicit namespace qualifications when you use a name. For example std::vector<int> v; (in headers, this should almost always be the only thing you do)

  3. Bring in all names, but in a reduced scope (like only inside a function). For example void f() { using namespace std; vector<int> v; } - this does not pollute the global namespace.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
2

The alternative is to write std:: everywhere. It's frowned upon because of name collisions and because it's unclear. If you just write vector I don't immediately know if you're using some math 3d vector or the standard library vector or something else. If you write std::vector it's clear. If you using namespace std, vector may collide with my own 3d math class called vector.

David
  • 27,652
  • 18
  • 89
  • 138