I found something that i cannot explain. Seen in VS, GCC and several online compilers.
In the example below, it looks like enum declaration is breaking the namespace. The example compiles and run.
How can the compiler resolve "MyToString" (second std::cout in main) without prepending the namespace?
Same happens when using enum class.
https://onlinegdb.com/9I6xu8OufQ
#include <iostream>
namespace NS
{
enum Color
{
RED,
GREEN,
BLUE
};
std::string MyToString(Color e)
{
return "SOMETHING";
}
}
int main()
{
std::cout << NS::MyToString(NS::Color::RED) << std::endl;
std::cout << MyToString(NS::Color::RED) << std::endl;
return 0;
}
If i move the enum declaration out of the namespace it no longer compiles (expected).
https://onlinegdb.com/Tmdh3_Vp6
#include <iostream>
enum Color
{
RED,
GREEN,
BLUE
};
namespace NS
{
std::string MyToString(Color e)
{
return "SOMETHING";
}
}
int main()
{
std::cout << NS::MyToString(Color::RED) << std::endl;
std::cout << MyToString(Color::RED) << std::endl;
return 0;
}
Adding "MyToString" outside namespace gives compile error: "'MyToString': ambiguous call to overloaded function" (Not expected).
https://onlinegdb.com/-r-3HzmCK
#include <iostream>
namespace NS
{
enum Color
{
RED,
GREEN,
BLUE
};
std::string MyToString(Color e)
{
return "SOMETHING";
}
}
std::string MyToString(NS::Color e)
{
return "SOMETHING";
}
int main()
{
std::cout << NS::MyToString(NS::Color::RED) << std::endl;
std::cout << MyToString(NS::Color::RED) << std::endl;
return 0;
}