如何"取消使用"命名空间?

Rod*_*ddy 77 c++ namespaces c++builder

我的开发系统(Codegear C++ Builder)的一个变幻莫测是,一些自动生成的头文件坚持要...

using namespace xyzzy
Run Code Online (Sandbox Code Playgroud)

...中的语句,当我最不想要或期望它时,它会对我的代码产生影响.

有没有办法可以以某种方式取消/覆盖以前的"使用"语句来避免这种情况.

也许...

unusing namespace xyzzy;
Run Code Online (Sandbox Code Playgroud)

Hea*_*eek 57

不.但是有一个潜在的解决方案:如果你将include指令包含在它自己的命名空间中,就像这样......

namespace codegear {
    #include "codegear_header.h"
} // namespace codegear
Run Code Online (Sandbox Code Playgroud)

...然后,该标头内的任何using指令的效果都被抵消了.

在某些情况下,这可能会有问题.这就是为什么每个C++样式指南都强烈建议不要在头文件中放置"using namespace"指令.

  • 在头文件中包含using指令也是一个糟糕的主意.这简单地缓解了这个问题. (23认同)
  • 将标头放在您自己的命名空间中不是解决方案,因为它会更改该库中声明的含义.(-1) (4认同)
  • 这完全取决于标题中声明的内容. (4认同)

jk.*_*jk. 47

不,你不能UNUSE命名空间.你唯一能做的就是把using namespace-statement放在一个块来限制它的范围.

例:

{
    using namespace xyzzy;

} // stop using namespace xyzzy here
Run Code Online (Sandbox Code Playgroud)

也许您可以更改自动生成的标题使用的模板.


Ecl*_*pse 15

您可能会在冲突时使用显式名称空间:

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
Run Code Online (Sandbox Code Playgroud)


cde*_*oix 10

供将来参考:由于XE版本有一个新值,您可以#define以避免using namespace System;包含在内的可怕内容:DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE


小智 7

如何使用sed,perl或其他命令行工具作为构建过程的一部分,在生成的头文件生成之后但在使用之前修改生成的头文件?