Namespace Conflict Resolution

I have a namespace with tons of characters that 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 can I resolve an "ambiguous" error without resorting to replacing "using namespace LottaStuff" with a thousand separate "using xxx;" statements?

Edit: Also, let's say I cannot edit my_file.cpp, only my_file.h. Thus, replacing OneMoreClass with MyCustomizations :: OneMoreClass everywhere, as suggested below, is not possible.

+4
source share
2 answers

The whole point of the namespace will fail when you say " using namespace ".

So take it and use namespaces. If you want to use the using directive, put it in main:

 int main() { using myCustomizations::OneMoreClass; // OneMoreClass unambiguously refers // to the myCustomizations variant } 

Understand what using directives do. You essentially have 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, and also put it in the main area. If you find that the namespace is really tedious, enter an alias:

 namespace ez = manthisisacrappilynamednamespace; ez::... 

But never use using namespace in the header and probably never in the global scope. This is good in local areas.

+8
source

You must explicitly specify which OneMoreClass you want:

 int main() { myCustomizations::OneMoreClass foo; } 
+3
source

Source: https://habr.com/ru/post/1305148/


All Articles