Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Telling the compiler that I am no longer using a namespace in C++

the syntax:

 using namespace x;

tells the compiler to find the symbols from namespace x. The situation becomes bad once you have a same symbol in two namespaces and you want to mutually use them. Is there a way to tell the compiler not to use a namespace? What I mean is something like this (namespaces x and y both have the function a)

using namespace x;
int k = a(); //x::a is called
drop namespace x; //imaginary syntax that I am looking for
using namespace y;
int j = a(); //y::a is called

"You must use scope resolution symbol '::'" is not the answer I am looking for.

like image 366
Amir Zadeh Avatar asked Apr 18 '13 21:04

Amir Zadeh


People also ask

What is the purpose of namespace in C?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Does C have using namespace?

Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it.

What is problematic about putting a using namespace directive at the start of your code?

The problem with putting using namespace in the header files of your classes is that it forces anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.

Is it good practice to use namespace?

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.


1 Answers

Since you don't want to use scope resolution, then create some additional scope:

{
    using namespace x;
    int k = a(); //x::a is called
}
{
    using namespace y;
    int j = a(); //y::a is called
}

I'm afraid this might turn to be worse than scope resolution, though :/

Edit:

One more thing (which I don't know if you're aware of) that might be helpful are namespace aliases. Say you've got a namespace with a disgustingly long name or multiple nested namespaces. You can shorten the name such as:

namespace x = very::weird::namespc::name;
namespace y = yabadabadoopdiedoo;
like image 76
jrok Avatar answered Oct 05 '22 12:10

jrok