如何从成员函数指针获取RTTI
我正在尝试将日志记录添加到一些调用许多成员函数指针之一的遗留代码中。想在调用成员函数之前打印它的名称。这只是为了调试(使用 C++17),它不必是可移植的或标准 C++(gcc 扩展就可以了)。尝试使用如下所示的 typeinfo 但它只显示类(而不是实际的成员函数)。
#include <iostream>
#include <typeinfo>
class myclass
{
public:
void foo() { }
};
int main()
{
auto x = &myclass::foo;
std::cout << typeid(x).name() << "\n";
}
在堆栈溢出的其他地方有一个非常聪明的技巧,您可以使用模板用函数指针及其名称(从 __PRETTY_FUNCTION__ 获取)来填充 std::map
,但它不适用于成员函数指针,因为(据我所知)成员函数指针无法保存在容器中。
有人有什么想法吗?
I'm trying to add logging to some legacy code that invokes one of many member function pointers. Would like to print the name of the member function before we call it. This is just for debugging (using C++17) and it doesn't have to be portable or standard C++ (a gcc extension would be fine). Tried using typeinfo like below but it only shows the class (not the actual member function).
#include <iostream>
#include <typeinfo>
class myclass
{
public:
void foo() { }
};
int main()
{
auto x = &myclass::foo;
std::cout << typeid(x).name() << "\n";
}
There's a very clever trick on elsewhere on stack overflow where you use templates to populate an std::map
with function pointers and their names (which you get from __PRETTY_FUNCTION__
) but it doesn't work with member function pointers because (as far as I can tell) member function pointers can't be saved in a container.
Anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论