Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: hiding some functions

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

  • I only include standard math.h or cmath headers within my math header, and that
  • I need to include standard math headers (because some of my functions are just wrappers for standard one, and I want them to be inline or they're templated),

is 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).

like image 813
peoro Avatar asked Dec 11 '10 11:12

peoro


3 Answers

Put this in a header file, and #include it everywhere:

namespace DontUseMe {  
double cos (double) ;  
// ...etc.  
}  
using namespace DontUseMe ;
like image 99
TonyK Avatar answered Oct 06 '22 15:10

TonyK


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)

like image 26
ltjax Avatar answered Oct 06 '22 15:10

ltjax


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.

like image 32
River Avatar answered Oct 06 '22 15:10

River