Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no way to undo 'using' in C++?

Tags:

c++

c++11

I've often found myself wanting a way to undo the effect of a using statement or to include all of a namespace (such as std) but exclude a bit to be replaced (such as cout). For some reason this isn't possible. I am wondering if anyone knows why it was decided not to add this ability to the language? Is there some technical reason? I assume it wasn't just forgotten since it doesn't seem slated for C++0x either.

Just to clarify, I'm not looking for workarounds since Google can show me those. I'm looking for an explanation of why this is impossible, and why it was not considered (as far as I can tell) for inclusion in 0x.

like image 329
mstearn Avatar asked Jul 02 '10 04:07

mstearn


3 Answers

A using directive brings a name or set of names into a given declarative scope.

You can't "un-using" for the same reason that you can't say

int x = 42;
// and later
[remove name x somehow]

There's no way to unintroduce names from a scope at all in C++, regardless where those names came from.

Given that it would overcomplicate name lookup (since names could be both added and removed from a scope), unless there is a really compelling use case, it's unlikely to be considered as a potential language feature.

like image 180
James McNellis Avatar answered Oct 27 '22 01:10

James McNellis


This is because the using directive is not meant to be used for native C++ code. It was intended to help migrate C code to C++. In this context, "un-using" doesn't make sense.

-edit- I should have been more specific. In this particular case, it looks like mstearn is using the using directive to include the std namespace globally. Doing this is generally a bad idea because it results in global namespace pollution, and should only be done in certain circumstances, like transitioning from another language to C++.

There are other situations where utilizing the using directive is fine (within a function, namespace composition). However "un-using" doesn't make sense in these situations either.

like image 25
aCuria Avatar answered Oct 27 '22 01:10

aCuria


Mostly because there are workarounds that are sufficiently simple and straightforward that virtually nothing would be gained by including a "feature" for that specific purpose. Though I'm not sure he ever states it directly, I think you could argue that one of the guidelines in the design of C++ has always been to prefer general mechanisms to special-purpose ones, so using the existing scope system (for example) makes more sense than adding some special way to remove something from a scope after it's been introduced.

like image 27
Jerry Coffin Avatar answered Oct 26 '22 23:10

Jerry Coffin