阻止第三方使用我的整个命名空间

时间:2016-06-18 19:53:19

标签: c++

虽然我已经搜索过,但我根本不知道这是否可行。

如何阻止图书馆用户在他/她的代码中的任何地方写using namespace myns;

我们说我实现了一个库,它将所有元素都包含在名为myns的名称空间中:

namespace myns
{
    class MyClass
    {

    };

    class string
    {

    };
}

该库将由另一位程序员使用。我怎样才能强迫他/她使用

// somewhere in code
myns::MyClass myClass;
myns::string myString;
std::string stdString;

而不是

using namespace myns;

// somewhere in code
MyClass myClass;
string myString; // this would most likely be a mess
string stdString;

这有助于命名空间冲突。

2 个答案:

答案 0 :(得分:3)

You can't. The standard says one can write using namespace myns; to get all the names, and there is nothing you can do about that.

If the user gets collisions after using namespace XXX;, that's his own fault. Generally, it is not possible to stop people from shooting themselves in the foot if they try to.

In the end, pulling in all names from some third party namespace is not something that happens on accident, but has been discouraged since about the dawn of time. If the user decides to do it anyways, he better knows what he his doing. Really not the problem of the library maintainer.

答案 1 :(得分:1)

我能想到的一个(可疑的)解决方法是使用同名的类或结构替换您的命名空间,并将命名空间中的所有内容转换为此类的(静态)成员。

struct myns final
{
    class MyClass
    {

    }

    class string
    {

    }

private:
    // private constructor, copy constructor and assignment operator
    // ...
};

这会阻止程序员使用您的库来编写using namespace myns但是......好吧,就像我说的那样,我认为这样的解决方案是非常值得怀疑的。

请注意,用户仍然可以使用类型别名,例如:

using string = myns::string;