如何在C ++中打印方法指针的地址? [英] How do I print the address of a method pointer in C++?
问题描述
例如:
struct A { void m() { } };
void stream_print() {
void(A::*p)(void) = &A::m;
std::cerr << p << std::endl;
}
void printf_print() {
void(A::*p)(void) = &A::m;
fprintf(stderr, "%p", p);
}
stream_print()函数总是输出1,这显然不是什么我想要。 printf_print不能编译,因为p不能转换为void *。
The stream_print() function always prints "1", which is obviously not what I want. The printf_print does not compile because p cannot be casted to void*.
我需要的是一个可以存储在容器中的方法指针的唯一标识符。我知道这听起来是一个坏主意,但我正在开发一个小玩具的单元测试,可以从中受益。我不担心方法的重载,我知道如何获得指向特定重载的指针。
What I need is a unique identifier for a method pointer that I can store in a container. I know this sounds like a bad idea, but I am developing a small toy for unit testing that can benefit from it. I am not worried about overloads of the method, I know how to get the pointer to a specific overload.
我使用g ++ 4.4.3与C ++ 0x启用
I am using g++ 4.4.3 with C++0x enabled.
如果您有任何疑问,请与我们联系。
Let me know if you have any doubts.
推荐答案
成员函数指针通常是一个具有非平凡内部结构的对象。这就是为什么你不能使用打印原始类型的工具打印它。将指针转换为 void *
是不可行的方法,因为成员指针的大小通常大于 sizeof(void *)
。强制转换为 void *
将在任何情况下丢弃指针表示的一部分,从而不再保证唯一性。
Member function pointer is generally an object with non-trivial internal structure. Which is why you can't print it using tools intended for printing primitive types. Casting the pointer to void *
is not a viable approach, since the size of member pointer is generally larger than sizeof(void *)
. Forcefully casting it to void *
will in any case discard a portion of the pointer representation, thus no longer guaranteeing the uniqueness.
如果您要查找的是从指针生成的唯一字符串,则可以将指针重新解释为字符数组,并使用标识符中字符值的字符串表示形式。像
If what you are looking for is a unique string generated from the pointer, you can reinterpret the pointer as a character array, and use the string representation of character values in the identifier. Something like
void (A::*p)(void) = &A::m;
for (size_t i = 0; i < sizeof p; ++i)
printf("%d ", reinterpret_cast<char *>(&p)[i]);
printf("\n");
这篇关于如何在C ++中打印方法指针的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!