目标是创建一个(宏?),当将其放置在类函数中时,它将为每个类实例(例如,this
指针)打印一个唯一的标识符,而在“正常”功能。最好不要在类中添加任何内容,但是如果这样做是唯一的方法,我将接受。
[这是我的尝试,但是它根本不喜欢使用this
(用(void)1
代替它可以工作,但是我希望每个类实例都有唯一的标识符。在gcc上,此错误显示为:error: invalid use of ‘this’ in non-member function
,而msvc具有类似的错误:error C2355: 'this': can only be referenced inside non-static member functions or non-static data member initializers
非工作代码:
#include <iostream>
class _detect_class_ {};
typedef int _class_sentinel_;
#define THIS_PTR std::is_same<_detect_class_, _class_sentinel_>::value ? (void*)this : nullptr
#define TRACK_THIS_OBJECT typedef _detect_class_ _class_sentinel_;
struct thisptr
{
void* Ptr;
thisptr(void* ptr): Ptr(ptr){;}
};
std::ostream& operator<<(std::ostream& strm, const thisptr& p)
{
if (p.Ptr)
strm << "Object:" << p.Ptr;
else
strm << "No object";
return strm;
}
#define PRINT_ME std::cout << thisptr(THIS_PTR) << std::endl;
struct TestStruct
{
void Function1()
{
PRINT_ME;
}
TRACK_THIS_OBJECT
};
int main()
{
TestStruct o1, o2;
PRINT_ME; // No object
o1.Function1(); // Object: (identifier1)
o2.Function1(); // Object: (identifier2)
return 0;
}
最简单的技巧是在顶层用一个称为“ this”的指针实例声明一个虚拟类。
我更改您的代码以添加空成员(C ++ 20)以具有预期的输出:
对于高级C++
专家来说,这可能太简单了>>
// this is in header pretty_print.h
#include <iostream>
inline void pretty_print() {}
#define PRINTABLE \
void pretty_print() { std::cout << this << std::endl; }
#define PRINT_ME pretty_print()
// end of header
// #include "pretty_print.h"
void moo() { PRINT_ME; }
struct Foo {
PRINTABLE
void foo() { PRINT_ME; }
};
int main() {
PRINT_ME;
moo();
Foo().foo();
}