|
||||
|
Section 33:
|
[33.10] Can I convert a pointer-to-member-function to a void*?
No!
class Fred {
public:
int f(char x, float y);
int g(char x, float y);
int h(char x, float y);
int i(char x, float y);
...
};
// FredMemFn points to a member of Fred that takes (char,float)
typedef int (Fred::*FredMemFn)(char x, float y);
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))
int callit(Fred& o, FredMemFn p, char x, float y)
{
return CALL_MEMBER_FN(o,p)(x, y);
}
int main()
{
FredMemFn p = &Fred::f;
void* p2 = (void*)p; // ← illegal!!
Fred o;
callit(o, p, 'x', 3.14f); // okay
callit(o, FredMemFn(p2), 'x', 3.14f); // might fail!!
...
}
Technical details: pointers to member functions and pointers to data are not
necessarily represented in the same way. A pointer to a member function might
be a data structure rather than a single pointer. Think about it: if it's
pointing at a virtual function, it might not actually be pointing at a
statically resolvable pile of code, so it might not even be a normal address
— it might be a different data structure of some sort.
Please do not email me if the above seems to work on your particular version of your particular compiler on your particular operating system. I don't care. It's illegal, period. |
|||