限制头文件中"using namespace"的范围

Limiting the scope of "using namespace" in a header file

本文关键字:using namespace 范围 文件      更新时间:2023-10-16

我正在使用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指令都只是扩展相应的头文件。这可以防止您以任何方式使头文件的内容与上下文相关。