I know that my compiler in the example below will execute the function First::fun(), because of Argument-Dependent name Lookup (ADL)/Koenig lookup and in order to execute Second::fun() this needs to be explicitly called in the main function.
#include <iostream>
using namespace std;
namespace First
{
enum Enum
{
FIRST
};
void fun(First::Enum symbol)
{
cout << "First fun\n";
}
}
namespace Second
{
void fun(First::Enum symbol)
{
cout << "Second fun\n";
}
}
int main()
{
fun(First::FIRST); // Calls First::fun()
}
However, when adding another function fun() outside of the namespaces (see code below) and calling fun() without a prefixed namespace the compiler gives an ambiguity error. The functions inside the namespaces can still be called by explicitly prefixing the namespace, but fun() is unreachable. Why doesn't the compiler prefer the function outside of the namespaces when none are explicitly called? Is there a specific reason this behaviour is avoided?
// ^ Namespaces are still here
fun(First::Enum symbol)
{
cout << "No namespace fun\n";
}
int main()
{
fun(First::FIRST); // Doesn't compile: ambiguity!
}
EDIT
As Yksisarvinen rightfully pointed out, the global fun() can still be called by prefixing with the global namespace: ::fun(First::FIRST);.
However, this still leaves me with the question: Why doesn't the compiler prefer the global fun() in the ambiguous call?