宏返回'this'指针,或 NULL (当指针不可用时)

Macro to return the 'this' pointer, or NULL when it's not available

本文关键字:指针 this 返回 NULL      更新时间:2023-10-16

是否可以在非静态上下文中访问this指针,并在静态上下文中自动使用其他指针?你知道宏或模板的魔力吗?

#define LOG std::cout << _is_the_this_pointer_available_ ? this : 0
class Foo {
  void test() {
    LOG;
  }
};
void staticTest() {
  LOG;
}

你知道宏或模板的魔力吗?

老实说,我不会用宏来做这件事。当某些事情可以在没有宏的情况下完成时,我建议避免使用它们。以下是一个基于重载、CRTP和继承(无宏(的可能解决方案:

int get_this() { return 0; }
template<typename T>
struct get_this_helper
{
    T* get_this() { return static_cast<T*>(this); }
};

唯一的开销是必须使类从get_this_helper<>的适当专业化派生,如下所示:

#include <iostream>
#define LOG std::cout << get_this() << std::endl;
class Foo : public get_this_helper<Foo> {
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//        This is the only thing that requires 
//        being changed wrt your version of Foo
public:
  void test() {
    LOG;
  }
};
void staticTest() {
  LOG;
}

这里有一个简单的测试程序:

int main()
{
    Foo f;
    f.test();
    staticTest();
}

还有一个活生生的例子。

我使用以下技术将这个指针写入日志:

#define GET_THIS() __if_exists(this) { this; } __if_not_exists(this) { nullptr; } 

然而,它是微软特有的。

#define LOG std::cout << isThisAvailable()
bool isThisAvailable() { return false; }
struct X
{
    bool isThisAvailable() { return true; }
    void test() { LOG; }
};
void staticTest()
{
   LOG;
}

在类内部调用isThisAvailable将返回true。在类上下文之外调用将调用free函数并返回false