Question

When one wants to store pointers to functions with different signatures, one might cast them to void(*)() (or any other function pointer type) then cast them back to original type before call and afaik C++ guarantees this round-trip to work. But what about member function pointers? Are there any guarantees that round-tripping a member function pointer through another member function pointer of different type (possibly to a member function of different class) will not break something?

Was it helpful?

Solution

Yes, a reinterpret_cast round-trip between pointer-to-member types is guaranteed to be valid, as long as you keep it pointer-to-data-member or pointer-to-member-function in both cases.

Quoting C++11:

[expr.reinterpret.cast]

10 A prvalue of type "pointer to member of X of type T1" can be explicitly converted to a prvalue of a different type "pointer to member of Y of type T2" if T1 and T2 are both function types or both object types. The null member pointer value (4.11) is converted to the null member pointer value of the destination type. The result of this conversion is unspecified, except in the following cases:

  • converting a prvalue of type "pointer to member function" to a different pointer to member function type and back to its original type yields the original pointer to member value.

OTHER TIPS

I think so with a reinterptret_cast. That's what the standard says (5.2.11/10)

A prvalue of type “pointer to member of X of type T1” can be explicitly converted to a prvalue of a different type “pointer to member of Y of type T2” if T1 and T2 are both function types or both object types.71 The null member pointer value (4.11) is converted to the null member pointer value of the destination type. The result of this conversion is unspecified, except in the following cases:

— converting a prvalue of type “pointer to member function” to a different pointer to member function type and back to its original type yields the original pointer to member value.

— converting a prvalue of type “pointer to data member of X of type T1” to the type “pointer to data member of Y of type T2” (where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer to member value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top