开发者

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

开发者 https://www.devze.com 2023-01-05 16:47 出处:网络
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\

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 t开发者_JAVA百科o 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消