jeudi 6 avril 2017

No ambiguous reference error even after using namespace directive

The following code generates call of overloaded ‘bar()’ is ambiguous error which it should be as I have a function bar in both global and foo namespace and I have called using namespace foo directive.

namespace foo {
    void bar() {}
}

void bar() {}

using namespace foo;

int main() {
    bar();
}

I was expecting the same error with the following code too:

#include <cstdlib>
#include <iostream>

int abs(int n) {
    return n > 0 ? n : -n;
}

using namespace std;

int main() {
    int k;

    cin >> k;

    cout << abs(k) << endl;
}

I have defined a function int abs(int n) like the one present in cstlib and I have called using namespace std directive. So there should have been an error like the first example. But there is none.

My question is how the compiler is resolving this ambiguity? Which function will be called in such cases, mine or std's one? Is there any UB involved here?

I have tested it with g++ 4.8.4 on Ubuntu 14.04 with -std=c++11 flag.

[Please note that I do understand that using namespace std is bad and my abs function is no better or even worse than std one. My question is different.]

Aucun commentaire:

Enregistrer un commentaire