Reading the answer to this question (Casting a function pointer to another type), I understand that it is safe to cast pointers like void(*)(A*)
to pointers like void(*)(B*)
, you just need to cast them back before calling them.
Does this also work for member function pointers? Can I safely cast void(A::*)()
to void(B::*)()
and cast it back before calling it?
Example code that seems to work at least on my system:
#include <iostream>
struct A {
void f() { std::cout << "called" << std::endl; }
};
struct B {};
int main() {
A instance;
auto ptr = reinterpret_cast<void (B::*)()>(&A::f);
(instance.*(reinterpret_cast<void (A::*)()>(ptr)))();
}