检测此可变可用性

时间:2019-03-07 19:46:12

标签: c++ c-preprocessor

我目前正在调整Windows C ++项目以使其在Linux上运行。 我定义了几个宏来将格式化的行打印到日志文件中。 它们就像printf一样,所以我可以这样写:

WARN("%d::%s<", 42, "baz");

打印类似这样的东西很容易

  

[thread_id] [WARN] [/ path / to / main.cpp:15] [2019年3月1日星期五   10:38:54.408] [this_value] 42 :: baz << / p>

this_value this 的值;如果未定义 this ,则为NULL(静态功能,外部的“ C”功能)。

我当前的代码是:

#if defined(_WIN32) && !defined(__INTELLISENSE__)
    #define SET_ZIS __if_exists (this) { zis = this; }
#else
    #define SET_ZIS
#endif

#define _LOG(...) \
    do \
    { \
        void *zis = NULL; \
        SET_ZIS \
        GetLoggerInstance()->logMessage(__VA_ARGS__); \
    } while(0)

#define LOG(...) _LOG(level, __FILE__, __LINE__, __func__, zis, __VA_ARGS__)
#define WARN(...) LOG(ILogger_level::LEVEL_WARN, __VA_ARGS__)

是否存在检测 是否存在的标准方法? 也许使用std::is_*或SFINAE技巧?

我使用外部的“ C”函数构造对象(“ this”是没有意义的),并调用实例对象(“ this”是有意义的)上的成员。 “构造函数”在共享对象中导出,并由C ++项目动态使用。这样,我就不必管理名称乱七八糟的东西。

extern "C" int CreateMyClass(std::shared_ptr<MyClass> *newClass);
int CreateMyClass(std::shared_ptr<MyClass> *newClass)
{
  RELAY("(%p)", newClass);
  *newClass = std::make_shared<MyClass>(42, "baz");
  return 0;
}

MyClass::MyClass(int a, char *b)
{
  RELAY("(%d,%s)", a, b);
}

编辑:这是一个简单的测试用例:

#include <memory> /* For std::shared_ptr */
#define RELAY(...) printf("[%p][%s]\n", this, __func__)

class MyClass
{
public:
  MyClass(int a, const char *b);
  static void test();
};

extern "C" int CreateMyClass(std::shared_ptr<MyClass> *newClass);
int CreateMyClass(std::shared_ptr<MyClass> *newClass)
{
  RELAY("(%p)", newClass);
  *newClass = std::make_shared<MyClass>(42, "baz");
  return 0;
}

MyClass::MyClass(int a, const char *b)
{
  RELAY("(%d,%s)", a, b);
}

void MyClass::test()
{
  RELAY("()");
  printf("some work");
}

int main(int argc, char **argv)
{
  std::shared_ptr<MyClass> newClass;

  int ret = CreateMyClass(&newClass);
  MyClass::test();
  return ret;
}

g ++出现以下错误:

test.c: In function ‘int CreateMyClass(std::shared_ptr<MyClass>*)’:
test.c:2:41: error: invalid use of ‘this’ in non-member function
 #define RELAY(...) printf("[%p][%s]\n", this, __func__)
                                         ^
test.c:14:3: note: in expansion of macro ‘RELAY’
   RELAY("(%p)", newClass);
   ^~~~~
test.c: In static member function ‘static void MyClass::test()’:
test.c:2:41: error: ‘this’ is unavailable for static member functions
 #define RELAY(...) printf("[%p][%s]\n", this, __func__)
                                         ^
test.c:26:3: note: in expansion of macro ‘RELAY’
   RELAY("()");
   ^~~~~

CreateMyClass不是静态的(“非成员函数”),因此不可用。静态函数也一样。

1 个答案:

答案 0 :(得分:-1)

this引用仅存在且始终存在于c ++类/结构的非静态成员函数中。它是一个函数正在操作的类实例的内存地址的指针。就日志记录而言,除了挖掘内存转储之外,我不确定您将如何使用它,而且我不确定100%的实例地址甚至对此有用。