如何“取消使用”名称空间?

我的开发系统(Codegear C + + Builder)的一个变化莫测的地方是,一些自动生成的头文件坚持使用..。

using namespace xyzzy

... 语句,这些语句在我最不想或最不期待的时候对我的代码产生影响。

有没有办法可以取消/覆盖之前的“ using”语句来避免这种情况。

也许..。

unusing namespace xyzzy;
49380 次浏览

No you can't unuse a namespace. The only thing you can do is putting the using namespace-statement a block to limit it's scope.

Example:

{
using namespace xyzzy;


} // stop using namespace xyzzy here

Maybe you can change the template which is used of your auto-generated headers.

Quick experiment with Visual Studio 2005 shows that you can enclose those headers in your own named namespace and then use what you need from this namespace (but don't use the whole namespace, as it will introduces the namespace you want to hide.

You may be stuck using explicit namespaces on conflicts:

string x; // Doesn't work due to conflicting declarations
::string y; // use the class from the global namespace
std::string z; // use the string class from the std namespace

Nope. But there's a potential solution: if you enclose your include directive in a namespace of its own, like this...

namespace codegear {
#include "codegear_header.h"
} // namespace codegear

...then the effects of any using directives within that header are neutralized.

That might be problematic in some cases. That's why every C++ style guide strongly recommends not putting a "using namespace" directive in a header file.

How about using sed, perl or some other command-line tool as part of your build process to modify the generated headers after they are generated but before they are used?

For future reference : since the XE version there is a new value that you can #define to avoid the dreaded using namespace System; int the include : DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE

#include<iostream>
#include<stdio.h>
namespace namespace1 {
int t = 10;
}
namespace namespace2 {
int t = 20;
}
int main() {
using namespace namespace1;
printf("%d" , t);
printf("%d" , namespace2::t);
}