Why I get error message (error: call of overloaded myCout() is ambiguous) when I use two different namespaces in same function making use of using namespace directive without fully qualified name space?
#include <iostream>
using namespace std;
namespace first
{
void myCout(void)
{
cout<<"Hello World is great\n";
}
}
namespace second
{
void myCout(void)
{
cout<<"Hello Sky is high\n";
}
}
int main(void)
{
cout<<"Hello World\n";
using namespace first;
myCout();
using namespace second;
myCout();
return(0);
}
If I use fully qualified namespaces for myCout() in second namespace as given below, there is no issue
int main(void)
{
cout<<"Hello World\n";
using namespace first;
myCout();
second::myCout();
return(0);
}
using directives respect scope. So you can introduce a new block scope to limit the availability of the symbols introduced by each:
int main(void)
{
cout<<"Hello World\n";
{
using namespace first;
myCout();
}
{
using namespace second;
myCout();
}
return(0);
}
Normally, and so as to avoid conflicts and deep nesting, try to pull in just the identifiers you need with a using declaration instead. If for instance you only ever wanted to use class foo from first then there would be no ambiguity with the following:
using first::foo;
using namespace second;
using namespace ... directives do not create an ordered path; nor do they override all previous ones. So, yes, your code creates an ambiguous situation.
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