宏返回'this'指针,或 NULL (当指针不可用时)
Macro to return the 'this' pointer, or NULL when it's not available
是否可以在非静态上下文中访问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
。
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 关于C++中具有多重继承"this"指针的说明
- Doees the 'this' 指针参与虚函数的多态行为
- 指针'this+1' C++中指的是什么?
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- Lambda 函数捕获错误的指针"this"
- 调用类的方法时,类的指针"this"变为 null C++
- 指针'this'可以是共享指针吗?
- 如何在C++中为指针'this'赋值
- C++:指针"this"没用吗?
- 指针"this"有什么问题?
- 将指针'this'传递为 LPARAM
- 错误 C2663:指针'this'重载没有合法转换
- C++ : 了解指针"this"
- 更改对象的指针'this'以指向不同的对象
- C++编译器是为所有成员方法生成指针"this"还是仅为引用成员的方法生成指针?
- 使用指针和不使用指针"this"有区别吗?
- 将enable_shared_from_这个基于类的指针(this)存储在itelf中
- 创建指向对象的指针"this"
- 如何在类中取消初始化指针"this"?