Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using different namespace in same function

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);
}
like image 991
Rajesh Avatar asked Sep 27 '26 21:09

Rajesh


2 Answers

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;
like image 79
StoryTeller - Unslander Monica Avatar answered Sep 30 '26 11:09

StoryTeller - Unslander Monica


using namespace ... directives do not create an ordered path; nor do they override all previous ones. So, yes, your code creates an ambiguous situation.

like image 23
Mischa Avatar answered Sep 30 '26 11:09

Mischa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!