Re: Handling void*
Seungbeom Kim wrote:
Martin T. wrote:
Thomas Maeder wrote:
No. There is not even a guarantee that converting from function
pointer to void * and later converting back to the function pointer
type yields a valid function pointer.
Hu?
I thought that's about the only thing guaranteed with void* pointers,
namely that I can cast them back to the original type??
int i;
void * pvi = &i; // OK
int* pi = static_cast<int*>(pvi); // OK (?)
That's true only for pointers to objects, not for pointers to functions
(3.9.2/4, 4.10/2, 5.2.9/10).
Pointers to functions can be converted only to pointers to functions
of other types by reinterpret_cast, and converted back to the original
type (5.2.10/6).
This is a hole in the type system. There is no portable way to display
the value of a function pointer; I.e. there is no
ostream& operator<<(ostream&, void(*)());
So, if, for debugging purposes, I want to dump a pointer to function, I
have to rely on inherently nonportable stuff, or else do something like
the following, which is byte-order dependent.
ostream& operator<<(ostream& os, void(*f)())
{
const unsigned char *p = reinterpret_cast<unsigned char *>(&f));
for (size_t j = 0 ; j < sizeof(f) ; ++j)
os << hex << *p++;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]