I've got a namespace 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.
XML namespaces can help resolve conflicts between element names. Namespaces solve the problem of collision between identically named elements. A namespace is a domain that contains a set of names. Shoe sizes make a good analogy.
There are several techniques for avoiding name collisions, including the use of: namespaces - to qualify each name within a separate name group, so that the totally qualified names differ from each other. renaming - to change the name of one item (typically the one used less often) into some other name.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification.
Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With