限制头文件中"using namespace"的范围
Limiting the scope of "using namespace" in a header file
我正在使用STL开发一个小型的个人c++项目。我不喜欢在我的头文件中到处都是"std::
",因为我发现它妨碍了可读性,但同时我不想在头文件中放置using namespace std
而引起自己的问题。
所以我想知道是否有办法限制using
声明的范围,以便它适用于我的头文件的内容,但是不适用于包含它的文件。我尝试了很多类似这样的事情
{
using namespace std;
// header file contents here
}
,但似乎不允许在函数定义之外以这种方式引入作用域。有办法做到我想要的吗?
请注意:我真的没有兴趣讨论这是不是一个好主意,我只是想知道它是否可以做到。
是的,我认为这是可以做到的。
为了实现这一点,您需要构建自己的名称空间。我已经写了一些代码,这是按预期工作。
头文件看起来像:
#include <iostream>
namespace my_space {
using namespace std;
void mprint ()
{
/*
* This is working. It means we can access
* std namespace inside my_space.
*/
cout << "AAA" << endl;
}
};
实现文件如下:
#include "my_header.h"
int main ()
{
/*
* Working Fine.
*/
my_space::mprint();
/*
* It gives a compile time error because
* it can't access the std namespace
*/
cout << "CHECK" << endl;
return 0;
}
如果不符合你的要求,请告诉我。我们可以商量商量。
不行。在头文件中引入作用域的尝试失败了,正是因为没有头文件作用域这样的东西——头文件在编译期间没有特殊的状态。翻译单元是预处理完成后得到的源文件。因此,所有include
指令都只是扩展相应的头文件。这可以防止您以任何方式使头文件的内容与上下文相关。
相关文章:
- "using namespace std;"在C++的作用是什么?
- 为什么我需要做'using namespace std'而不是"使用 std::cout"?
- 'using namespace'实现细节的便捷方法(仅标头库)?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- "using namespace"子句在什么范围内有效?
- 如何找到"using namespace std"的违规用法?
- 在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?
- 如何根据对象名称将'using namespace'添加到类定义中?
- 没有任何 #include "using namespace std;"?
- 用于定义全局函数"using namespace"
- 'using namespace'如何在C++运作
- 为什么我们应该在使用"using namespace std"时使用"#include<iostream>"?
- 如何在代码中使用 STD 而不包含"using namespace std"?
- 如何正确使用"using namespace foo?"
- 使用不带前缀"std"且不带"using namespace std;"的 std::sort() 成功编译
- 总是"using namespace std" ?
- 头文件中可以包含"using namespace"语句吗?
- 为什么以及如何"using namespace"声明会混淆C++中的编译器?
- "using namespace std;"是否免于过多代码规则?
- C++如何知道在哪里查找使用 "using namespace ..." 指定的命名空间?