Check/test this code on https://repl.it/@JomaCorpFX/NameCollision#main.cpp
#include <iostream>
namespace std{
static int Add(int a, int b)
{
return a + b;
}
}
namespace math{
static int Add(int a, int b)
{
return a + b;
}
}
static int Add(int a, int b)
{
return a + b;
}
using namespace std;
using namespace math;
int main() {
std::cout << std::Add(1,2) << std::endl; //OK
std::cout << math::Add(1,2) << std::endl; //OK
std::cout << ::Add(1,2) << std::endl; //OK
std::cout << Add(1,2) << std::endl;//ERROR. Ambiguous call to "std::Add" or "math::Add" or local function "Add" // Comment this line for fix the error or complete the correct namespace or delete using namespace statements.
}
Output when compile
main.cpp:29:16: error: call to 'Add' is ambiguous
std::cout << Add(1,2) << std::endl;//ERROR. Ambiguous call to "std::Ad...
^~~
main.cpp:4:14: note: candidate function
static int Add(int a, int b)
^
main.cpp:11:14: note: candidate function
static int Add(int a, int b)
^
main.cpp:17:12: note: candidate function
static int Add(int a, int b)
^
1 error generated.
compiler exit status 1
If you type "using namespace std" statement you can incurr in function name/signature collision, another headers can contains the same function signature without a namespace.
Your original code can breaks if you include a new header that can contains 1 or n functions which math the signature with your code. The compiler shows errors in code, many headaches.
Best practice is use the complete name, to avoid this. Spend more time, gain more readabilty and have less errors.
std::Add
math::Add
::Add
std::cout
std::string
For convention only C++ standard library can have the namespace std.