【问题标题】:Resolving namespace conflicts解决命名空间冲突
【发布时间】:2011-01-31 21:44:27
【问题描述】:

我有一个包含大量符号的命名空间,但我想覆盖其中一个:

external_library.h

namespace LottaStuff
{
class LotsOfClasses {};
class OneMoreClass {};
};

我的文件.h

using namespace LottaStuff;
namespace MyCustomizations
{
class OneMoreClass {};
};
using MyCustomizations::OneMoreClass;

my_file.cpp

int main()
{
    OneMoreClass foo; // error: reference to 'OneMoreClass' is ambiguous
    return 0;
}

如何解决“歧义”错误,而不用一千个人“使用 xxx;”替换“使用命名空间 LottaStuff”声明?

编辑:另外,假设我不能编辑 my_file.cpp,只能编辑 my_file.h。因此,不可能按照下面的建议在任何地方用 MyCustomizations::OneMoreClass 替换 OneMoreClass。

【问题讨论】:

  • 这里有一个提示——不要使用“using”关键字,而是使用完全限定名来引用类:vector -> ::std::vector !
  • C++11 将有一个很好的功能来控制版本命名空间(内联命名空间),这将允许用户准确地得到这个......再说一次,你可能需要等待比你想要的更多的时间编译器中的功能(除非您使用 gcc >4.4)open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2535.htm

标签: c++ namespaces


【解决方案1】:

当你说“using namespace”时,命名空间的全部意义就被打败了。

所以拿出来使用命名空间。如果你想要一个 using 指令,把它放在 main:

int main()
{
    using myCustomizations::OneMoreClass;

    // OneMoreClass unambiguously refers
    // to the myCustomizations variant
}

了解using 指令的作用。你所拥有的基本上是这样的:

namespace foo
{
    struct baz{};
}

namespace bar
{
    struct baz{};
}

using namespace foo; // take *everything* in foo and make it usable in this scope
using bar::baz; // take baz from bar and make it usable in this scope

int main()
{
    baz x; // no baz in this scope, check global... oh crap!
}

一个或另一个将起作用,以及将一个放在main 的范围内。如果您发现命名空间的键入确实很乏味,请创建一个别名:

namespace ez = manthisisacrappilynamednamespace;

ez::...

但从不在标头中使用using namespace,并且可能从不在全局范围内。在本地范围内没问题。

【讨论】:

    【解决方案2】:

    您应该明确指定您想要的OneMoreClass:

    int main()
    {
        myCustomizations::OneMoreClass foo;
    }
    

    【讨论】:

    • 如果我不能编辑 my_file.cpp 怎么办?编辑了我上面的问题。
    • @Kyle:那就停止使用using namespace。你不能使用它然后抱怨命名空间冲突。这就像你的车里有安全带,但你撕掉它们然后抱怨你不安全。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2016-02-20
    • 1970-01-01
    • 2023-04-03
    • 2010-09-20
    相关资源
    最近更新 更多