如何判断当前函数是C++11中的正则成员函数还是静态成员函数

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

本文关键字:函数 成员 静态成员 C++11 何判断 判断      更新时间:2023-10-16

我将尝试解释我要做的事情:

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 datan";
   }
   static void staticMem() {
      LOGFILE << "Some datan";
   }
 };

我试图修改LOGFILE定义,使其仅在基于if_filter_applies()成员函数的输出从类的成员函数中使用时写入流。

如果从类外或静态成员函数中使用LOGFILE,我希望它使用全局if_filter_applies()函数(它总是返回true)。

上面的代码没有编译,因为static void staticMem()最终使用if_filter_applies()类成员而不是全局成员。

我不想创建类似于#define LOGFILE的不同定义来替换静态成员函数,因为我们的代码中有数百个文件,我不想手动替换所有出现的文件。

那么,我可以对#defile LOGFILE宏进行任何更改,以便它在静态成员函数的上下文中调用::if_filter_applies()吗?

如果您使用的是MS Visual Studio,则可以对this使用__if_exists检查。所以类似于:

__if_exists(this)
{
    // In a member function
}
__if_not_exists(this)
{
    // Not in a member function
}