开发者

Resolving namespace conflicts

开发者 https://www.devze.com 2022-12-24 08:48 出处:网络
I\'ve got a n开发者_开发知识库amespace with a ton of symbols I use, but I want to overwrite one of them:

I've got a n开发者_开发知识库amespace with a ton of symbols I use, but I want to overwrite one of them:

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

How do I get resolve the 'ambiguous' error without resorting to replacing 'using namespace LottaStuff' with a thousand individual "using xxx;" statements?

Edit: Also, say I can't edit my_file.cpp, only my_file.h. So, replacing OneMoreClass with MyCustomizations::OneMoreClass everywhere as suggested below wouldn't be possible.


The entire point of namespaces is defeated when you say "using namespace".

So take it out and use namespaces. If you want a using directive, put it within main:

int main()
{
    using myCustomizations::OneMoreClass;

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

Understand what using directives do. What you have is essentially this:

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!
}

One or the other will work, as well as placing one within the scope for main. If you find a namespace truly tedious to type, make an alias:

namespace ez = manthisisacrappilynamednamespace;

ez::...

But never use using namespace in a header, and probably never in global scope. It's fine in local scopes.


You should explicitly specify which OneMoreClass you want:

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

精彩评论

暂无评论...
验证码 换一张
取 消