gpt4 book ai didi

c++ - 返回 'this' 指针的宏,当它不可用时返回 NULL

转载 作者:搜寻专家 更新时间:2023-10-30 23:59:34 25 4
gpt4 key购买 nike

是否可以在非静态上下文中访问 this 指针并在静态上下文中自动使用其他内容?您知道任何宏或模板魔法吗?

#define LOG std::cout << _is_the_this_pointer_available_ ? this : 0

class Foo {
void test() {
LOG;
}
};

void staticTest() {
LOG;
}

最佳答案

Do you know any macro or template magic?

老实说,我不会用宏来做这件事。如果可以 宏来完成某些事情,我建议最好避免使用它们。这是基于重载、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();
}

还有一个 live example .

关于c++ - 返回 'this' 指针的宏,当它不可用时返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15923577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com