Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell whether the current function is a regular or a static member function in C++11?

I'll try to explain what I'm trying to do:

bool if_filter_applies() {return true;}

#defile LOGFILE if( if_filter_applies() ) LOG_STREAM_OBJECT

void globalFunc() { LOGFILE << "Some data \n"; }

class C {
    int a;
    bool if_filter_applies() {
       if ( a == 1)
          return true;
       else
          return false;
       }
 public:
   void regMem () {
      LOGFILE << "Some data\n";
   }
   static void staticMem() {
      LOGFILE << "Some data\n";
   }
 };

I'm trying to modify a LOGFILE definition so that it ONLY writes to a stream when used from within a class's member function based on the output of the if_filter_applies() member function.

If LOGFILE is used from outside the class or in a static member function, I want it to use the Global if_filter_applies() function (which always returns true).

The above code does not compile, because static void staticMem() ends up using the if_filter_applies() class member instead of the global.

I don't want to create a different definition similar to #define LOGFILE as a replacement specifically for static member functions, because there are hundreds of files in our code and I don't want to replace all occurrences manually.

So are there any changes I can make to #defile LOGFILE macro so that it calls ::if_filter_applies() instead in the context of a static member function?

like image 782
SidR Avatar asked Mar 30 '16 05:03

SidR


1 Answers

If you're using MS Visual Studio, you can use the __if_exists check against this. So something like:

__if_exists(this)
{
    // In a member function
}
__if_not_exists(this)
{
    // Not in a member function
}
like image 107
Buddy Avatar answered Nov 05 '22 12:11

Buddy