据我所知,C++标准允许将函数指针转换为不同的类型(只要不调用它们):
int my_func(int v) { return v; }
int main() {
using from_type = int(int);
using to_type = void(void);
from_type *from = &my_func;
to_type *to = reinterpret_cast<to_type *>(from);
// ...
}
此外,如果我将指针转换回其原始类型并调用它,则不会出现未定义的行为。
到目前为止,一切都很好。那么接下来呢?
const bool eq = (to == reinterpret_cast<to_type *>(my_func));
在转换后地址是否也仍然有效并非标准所保证。
虽然这与问题无关,但可能情况是当采用类型擦除技术时。如果地址仍然有效,则可以在不知道原始函数类型的情况下完成某些操作。