使用预先制作的命名空间进行范围界定(c++)

Scoping with pre-made namespace (C++)

本文关键字:范围 c++ 命名空间      更新时间:2023-10-16

为了避免STL中的所有内容的作用域,您可以键入

using namespace std;

为了避免只限定少量内容的作用域,您可以输入:

using std::cout;  
using std::cin;

我想编写一个以相同方式工作的库。但是,我希望能够包含特定的函数集合,而不是能够包含特定的类。

例如,我写:

  • 字符串函数的集合
  • 数学函数集合

它们是同一个命名空间的一部分,但我可以包括我想要的块


这是一个sudo-ish代码,但我认为它明白了我的意思:

namespace Everything{
    namespace StringFunctions{
        void str1(string & str);
        void str2(string & str);
        void str3(string & str);
        void str4(string & str);
        void str5(string & str);
    }
    namespace MathFunctions {
        void math1(int & num);
        void math2(int & num);
        void math3(int & num);
        void math4(int & num);
        void math5(int & num);
    }
}

,那么我希望能够这样做:

#include "Everything.h"
using Everything::Stringfunctions;
int main(){
    str1("string"); //this works, I can call this!
    math1(111);     //compile error: I've never heard of that function!
    return 0;
}

显然这不起作用,我对如何划分我的库有点困惑。我不想让它们成为类,然后不得不到处使用"点运算符",但我也不想包含大量的头文件。

也许我走错了路。我希望每个人都能帮助我采取正确的方法。


编辑:

可以这样写:

using namespace Everything::Stringfunctions;

您所给出的示例中编写库的方式已经足够了。

人们可以通过使用指令using namespace Everything::Stringfunctions从命名空间Everything::Stringfunctions获得所有功能。

无论如何您都应该考虑将功能拆分为不同的头文件,否则您将以噩梦般的编译时间告终。也就是说,我认为using namespace Everything::Stringfunctions;应该做这个(和多余的namespace在一起)。

如果您使用using namespace而不仅仅是using,那么您想要的似乎是有效的。请看这里(程序编译并输出'5')