I redefined some maths functions (so that they're faster -ie: less accurate-, or use templates). I put these functions in a namespace and they work just fine.
It happens often, though, that I forget to call functions from my namespace (ie: I forget to write mymath::cos
or using mymath::cos;
when I want to call cos
), and it's pretty tough to find out where I forgot it (until now I found it out only by profiling).
Given that
math.h
or cmath
headers within my math header, and thatis there a portable way to hide standard math function so that a compile error is reported, if global namespace (ie: without a namespace) math functions are used?
A solution could be putting an using namespace mymath;
at the bottom of my math header file, but this solution doesn't seem that great: it breaks the whole purpose of namespaces; I'd prefer having to explicity say whether to use a function from mymath
or from std
so that I am forced to choose between a fester or a more accurate function without the risk of forgetting about it.
EDIT:
Many answers say that if I use cos
from global namespace (without using std
nor mymath
), and include cmath
(and not math.h
), compilation should fail.
I don't know what the standard says about it, but:
#include <cmath>
int main( ) {
cos( M_PI );
return 0;
}
compiles fine with GNU GCC (g++
) 4.5.1 (and older versions).
Put this in a header file, and #include it everywhere:
namespace DontUseMe {
double cos (double) ;
// ...etc.
}
using namespace DontUseMe ;
If you only include cmath
and not math.h
, all functions from that header should be in the std:: namespace. Just never use using namespace std;
and you'll be fine. (cmath
is just math.h
with all things in a namespace)
Do you need to include the math.h and cmath headers directly in your header file? If you do need to, try including the header like this:
namespace arbitrary_name
{
#include <math.h>
}
This will contain all of the math.h definitions inside a new namespace, so you won't accidentally use them elsewhere.
This is not ideal solution. Perhaps there is a better way to do this using anonymous namespaces, but the solution isn't clear to me.
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