Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to not use an item from a namespace?

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?

like image 544
Telescope Avatar asked Jun 11 '20 16:06

Telescope


2 Answers

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.

like image 99
Jesper Juhl Avatar answered Sep 29 '22 09:09

Jesper Juhl


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

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

like image 44
David G. Pickett Avatar answered Sep 29 '22 07:09

David G. Pickett