我怎样才能“不使用”命名空间?
-
03-07-2019 - |
题
我的开发系统(Codegear C ++ Builder)的一个变幻莫测是,一些自动生成的标头坚持要......
using namespace xyzzy
...其中的语句,当我最不想要或期望它时会对我的代码产生影响。
有没有办法可以某种方式取消/覆盖之前的“使用”声明,以避免这种情况。
也许......
unusing namespace xyzzy;
解决方案
不。但是有一个潜在的解决方案:如果你将include指令包含在它自己的命名空间中,就像这样......
namespace codegear {
#include "codegear_header.h"
} // namespace codegear
...然后,该标题内任何using指令的效果都会被中和。
在某些情况下,这可能会有问题。这就是为什么每个C ++样式指南强烈建议不放置“using namespace”。头文件中的指令。
其他提示
不,你不能不使用命名空间。你唯一能做的就是把 using namespace
-statement一个块来限制它的范围。
示例:
{
using namespace xyzzy;
} // stop using namespace xyzzy here
也许您可以更改自动生成的标题使用的模板。
您可能会在冲突时使用显式命名空间:
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
供将来参考:由于XE版本有一个新值,您可以#define以避免使用命名空间系统的可怕;
int包含:DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE
如果使用sed,perl或其他一些命令行工具作为构建过程的一部分,在生成标头生成后但在使用它们之前修改生成的标头怎么样?
使用Visual Studio 2005进行快速实验表明,您可以将这些标头包含在您自己的命名空间中,然后使用
从此命名空间中获取所需内容(但不要使用
整个命名空间,因为它将引入您想要隐藏的命名空间。
#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);
}
不隶属于 StackOverflow