解决命名空间冲突

6

我有一个命名空间,其中有很多我使用的符号,但我想覆盖其中一个:

external_library.h

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

my_file.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;
}

我该如何解决“ambiguous”错误,而不是用数千个“using xxx;”语句来替换“using namespace LottaStuff”?
编辑:还有,假设我无法编辑my_file.cpp,只能编辑my_file.h。因此,像下面建议的那样在所有地方将OneMoreClass替换为MyCustomizations :: OneMoreClass是不可能的。

2
这里有一个提示 - 不要使用 "using" 关键字,而是使用完全限定名称引用类:vector<> -> ::std::vector<>! - Poni
C++11将具有用于版本命名空间的良好功能(内联命名空间),这将允许用户准确地获得此功能...但是,除非您使用gcc> 4.4,否则您可能需要等待更长时间才能在编译器中使用该功能。http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2535.htm - David Rodríguez - dribeas
2个回答

10

当你说 "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,并且可能永远不要在全局作用域中使用。在局部作用域中使用是可以的。

千万不要在头文件中使用using namespace,而且很可能也不要在全局范围内使用。在局部范围内使用是可以的。


3

你需要明确指定你想要的OneMoreClass

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

如果我无法编辑my_file.cpp怎么办?我已经修改了我的问题。 - Kyle
3
@Kyle: 那就不要使用 using namespace。你不能使用它,然后抱怨命名空间冲突。这就像有座椅安全带的车子,但你把它们撕下来,然后抱怨说不安全。 - GManNickG

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接