I have a question regarding function declaration scopes in C++. Suppose using #include <cmath>
introduces a function symbol into the global namespace. According to my understanding, in principle, it should only introduce symbols into the std
namespace, but in practice, from my own experience, some symbols appear in the global namespace. This answer seems to confirm this: cmath header confusion.
Now, what happens when I declare a function (with the same prototype as the function from the global namespace) inside a namespace foo { }
? Suppose for example, that sqrt()
from <cmath>
ends up in the global namespace, and I have:
#include <cmath>
namespace foo {
template <class T>
T sqrt( T x ) {
// do something extra...
return std::sqrt( x );
}
}
// ...
void foo::bar() {
double a = 4.0;
double b = sqrt( a );
}
The template is resolved to the symbol double sqrt( double x )
, which seems like it should clash with the one in the global namespace. It seems to work, but is this generally a bad practice?
More generally, does a function declared inside a namespace take precedence over a global function, when used from inside the same namespace? Does this violate the C++ standard in any way?