2

Possible Duplicate:
How can I “unuse” a namespace?

After declaring "using namespace mynamespace", for example, is it possible to stop using that namespace mid-code?

Thanks for your help.

Community
  • 1
  • 1
JonaGik
  • 1,533
  • 5
  • 24
  • 35

3 Answers3

3

Take a look at the C++ documentation on Namespaces.

http://www.cplusplus.com/doc/tutorial/namespaces/

You can declare that you are 'using' a namespace for a specific scope (such as a function). But I don't believe you can arbitrarily specify where a using statement starts and ends, it is always for the rest of the scope it is declared in.

I should note (someone please correct me if I'm wrong) that in C++ you can arbitrarily declare a scope almost anywhere you want, simply by using curly braces.

{ 
  using mynamespace;
  /* rest of your code here */
}

But use it sparingly and carefully, because if used too often or in the wrong context, it can make code harder to read (which defeats the whole point of 'using' in the first place, right?).

Nathan Bell
  • 2,364
  • 2
  • 18
  • 16
  • "entire scope"... rest of the scope... 8-) – Tony Delroy Jun 20 '11 at 04:32
  • @Tony I'm not a seasoned C++ programmer. Is it really just the rest of the scope? If so I'll edit my answer. I'm used to languages with two-pass compilers that apply it to the whole scope. – Nathan Bell Jun 20 '11 at 04:35
  • the only place C++ uses 2 passes is class/struct content, and then it's to allow ordering of content by access specifier or functionality. – Tony Delroy Jun 20 '11 at 04:59
3

You cannot stop using namespace in your code. But you can do some smart changes to your code to simulate that effect.

  1. Splitting into various .cpp files and use using namespace into only those files where actually needed
  2. In the same file, keep the code with using namespace facility towards the bottom of the file, so that upper code will not be having the using effect.
  3. Enclosing the using namespace inside another namespace / function. See example.
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • Re 3, function, block and namespace scope work. (`class`/`struct`/`union` doesn't allow using namespace, and `using` of functions is supported exclusively for base class methods.) – Tony Delroy Jun 20 '11 at 05:22
  • @Tony, yes that's why I haven't mention `class/struct/union`. In fact I myself had asked a question regarding it some days ago. http://stackoverflow.com/questions/6326805/why-using-namespace-x-is-not-allowed-inside-class-struct-level – iammilind Jun 20 '11 at 05:27
  • well, your question gets a +1 from me as well then :-) – Tony Delroy Jun 20 '11 at 05:36
0

No, I think that namespace will be available to you for entire .cpp file, but if you want to use an object of same name from some other namespace you can always use fully qualified name!

love Computer science
  • 1,824
  • 4
  • 20
  • 39