7

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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.