6

I've learned that typing

using namespace std;

at the beginning of a program is a bad habit, because it includes every function in the namespace. This risks causing errors if there is a name collision.

My question is, does there exist a way to specify which namespace functions you don't want to use? Is there some statement, such as

not_using std::cin;

that can accomplish this?

Telescope
  • 2,068
  • 1
  • 5
  • 22

3 Answers3

12

You cannot do that (include everything and then selectively exclude something).

Your options are:

1) always explicitly qualify names. Like std::vector<int> v;

2) pull in all names with using namespace std;

3) pull in just the names you need with, for example, using std::vector; and then do vector<int> v; - names other than "vector" are not pulled in.

Note: using namespace std; doesn't have to go at global scope and pollute the entire file. You can do it inside a function if you want:

void f() {
    using namespace std;
    // More code
}

That way, only f() pulls in all names in its local scope. Same goes for using std::vector; etc.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
2

You can using ns_name::name; just the name's you want unqualified access to.

https://en.cppreference.com/w/cpp/language/namespace

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

Instead of using global namespace scope, use this syntax : For example : std::cout :

For more examples read this : http://www.cplusplus.com/doc/tutorial/namespaces/

Cypress
  • 55
  • 1
  • 8