如何获取成员函数的字符串表示形式?
How to get string representation for the member function?
作为散列的一部分,我需要将函数指针转换为字符串表示形式。使用 global/static 函数很简单:
string s1{ to_string(reinterpret_cast<uintptr_t>(&global)) };
并且来自 here:
2) Any pointer can be converted to any integral type large enough to
hold the value of the pointer (e.g. to std::uintptr_t
)
但是我的成员函数有问题:
cout << &MyStruct::member;
输出 1
虽然在调试器中我可以看到地址。
string s{ to_string(reinterpret_cast<uintptr_t>(&MyStruct::member)) };
给出编译时错误cannot convert
。所以好像不是任何指针都可以转换。
我还能做些什么来获得字符串表示形式?
cout << &MyStruct::member;
outputs 1
though in debugger I can see the address.
ostream::operator<<(decltype(&MyStruct::member))
没有重载。但是,成员函数指针可隐式转换为 bool
,为此,存在重载,这是重载解析的最佳匹配。如果指针不为空,则转换后的值为 true
。 true
输出为 1
.
string s{ to_string(reinterpret_cast<uintptr_t>(&MyStruct::member)) };
Gives a compile-time error cannot convert. So it seems that not any pointer can be converted.
也许令人困惑,在标准语中 pointer 不是对象指针、指向成员的指针、指向函数的指针和指向成员函数的指针的总称。指针具体指的只是数据指针。
因此,引用的规则不适用于指向成员函数的指针。它仅适用于(对象)指针。
What else can I do to get a string representation?
可以使用unsigned char
的缓冲区,大到足以表示指针,然后使用std::memcpy
。然后以您自己选择的格式打印。我推荐十六进制。
正如 Martin Bonner 指出的那样,指向成员的指针可能包含填充,在这种情况下,指向同一成员的两个值在缓冲区中实际上可能具有不同的值。因此,打印的值没有多大用处,因为两个值在不知道哪些位(如果有)正在填充的情况下无法比较 - 这是实现定义的。
Unfortunately I need a robust solution so because of this padding I can't use.
不存在 便携 可靠的解决方案。
正如 Jonathan Wakely 指出的那样,Itanium ABI 中没有填充,因此如果您的编译器使用它,那么建议的 memcpy 方法就可以工作。
作为散列的一部分,我需要将函数指针转换为字符串表示形式。使用 global/static 函数很简单:
string s1{ to_string(reinterpret_cast<uintptr_t>(&global)) };
并且来自 here:
2) Any pointer can be converted to any integral type large enough to hold the value of the pointer (e.g. to
std::uintptr_t
)
但是我的成员函数有问题:
cout << &MyStruct::member;
输出 1
虽然在调试器中我可以看到地址。
string s{ to_string(reinterpret_cast<uintptr_t>(&MyStruct::member)) };
给出编译时错误cannot convert
。所以好像不是任何指针都可以转换。
我还能做些什么来获得字符串表示形式?
cout << &MyStruct::member;
outputs
1
though in debugger I can see the address.
ostream::operator<<(decltype(&MyStruct::member))
没有重载。但是,成员函数指针可隐式转换为 bool
,为此,存在重载,这是重载解析的最佳匹配。如果指针不为空,则转换后的值为 true
。 true
输出为 1
.
string s{ to_string(reinterpret_cast<uintptr_t>(&MyStruct::member)) };
Gives a compile-time error cannot convert. So it seems that not any pointer can be converted.
也许令人困惑,在标准语中 pointer 不是对象指针、指向成员的指针、指向函数的指针和指向成员函数的指针的总称。指针具体指的只是数据指针。
因此,引用的规则不适用于指向成员函数的指针。它仅适用于(对象)指针。
What else can I do to get a string representation?
可以使用unsigned char
的缓冲区,大到足以表示指针,然后使用std::memcpy
。然后以您自己选择的格式打印。我推荐十六进制。
正如 Martin Bonner 指出的那样,指向成员的指针可能包含填充,在这种情况下,指向同一成员的两个值在缓冲区中实际上可能具有不同的值。因此,打印的值没有多大用处,因为两个值在不知道哪些位(如果有)正在填充的情况下无法比较 - 这是实现定义的。
Unfortunately I need a robust solution so because of this padding I can't use.
不存在 便携 可靠的解决方案。
正如 Jonathan Wakely 指出的那样,Itanium ABI 中没有填充,因此如果您的编译器使用它,那么建议的 memcpy 方法就可以工作。