As I understand it, in C++03 #include <cmath>
must declare the functions only in namespace std
. Since C++11 they may additionally be declared in global namespace. This is the result of the practice where most C++ implementations declared the functions in global namespace (presumably #include
ing <math.h>
), and then just did using ::acos;
etc. in namespace std
.
But it seems to me that it would be similarly easy for the implementations to do something like this in their <cmath>
:
namespace __C_LANGUAGE_MATH_H
{
#include <math.h>
}
// ...
namespace std
{
// ...
using __C_LANGUAGE_MATH_H::acos;
// ...
}
Why wasn't this practiced instead of just polluting the global namespace? Does my suggested solution have some major drawbacks which made the C++ committee allow pollution of global namespace in C++11?
NOTE: this does work, and linker gives no errors, at least with GCC + Binutils-ld. I've actually tried and edited GCC's cmath
file like follows, and compiled my project which actively uses cmath
functions successfully (after fixing some calls which mistakenly didn't specify std::
in the project):
mv /usr/include/c++/5.3.0/cmath{,.bak}
sed -i -e 's@\(# *include <math.h>\)@namespace __C_LANGUAGE_MATH_H\n{\n\1\n}@' \
-e 's@\(using \+\)::@\1__C_LANGUAGE_MATH_H::@' /usr/include/c++/5.3.0/cmath
As stated in corresponding issue discussion in gcc bugzilla this approach will not allow including C header after C++ because of include guards:
#include <cmath>
#include <math.h> // include skipped by include guards
...
sin(x); // error: no sin in global namespace
As you mentioned standard requirements to C library wrappers were changed after issue was posted in defect report and previous requirements have been declared impractical from implementation point of view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With