Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 宏返回';这';指针,当它为';没有_C++_Templates_Macros - Fatal编程技术网

C++ 宏返回';这';指针,当它为';没有

C++ 宏返回';这';指针,当它为';没有,c++,templates,macros,C++,Templates,Macros,是否可以在非静态上下文中访问此指针,并在静态上下文中自动使用其他内容?你知道宏或模板魔术吗 #define LOG std::cout << _is_the_this_pointer_available_ ? this : 0 class Foo { void test() { LOG; } }; void staticTest() { LOG; } #定义日志标准::cout#定义日志标准::cout 你知道宏或模板魔术吗 #define LOG std:

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

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

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

void staticTest() {
  LOG;
}
#定义日志标准::cout
#定义日志标准::cout
你知道宏或模板魔术吗

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

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

void staticTest() {
  LOG;
}
老实说,我不会用宏来做这件事。如果没有宏就可以完成某些事情,我建议您最好避免使用宏。下面是一个基于重载、CRTP和继承(无宏)的可能解决方案:


和a.

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

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

但是,这是Microsoft特有的。

您想实现什么?宏在函数/类作用域已知之前的某个级别上运行,因此它们不会这样做。此外,C++没有提供任何特定的特性来检测您是否处于非静态成员函数中。但每个类都需要一个函数。也不会为类内的静态方法编译-。@Dukeling是的。太糟糕了:))不幸的是,我想在不强制所有类都为helper子类的情况下实现这一点…@LeventeMészáros:没有标准的、可移植的方法来实现这一点。您使用的编译器是什么?多个编译器:MS VC、gcc、多平台上的clang:windows、linux、,mac@LeventeM塞萨罗斯:我可能错了,但在这种情况下,恐怕这是你能做到的。@LeventeM塞萨罗斯:没问题:)
#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; }