举个例子:https ://godbolt.org/z/gHqCSA
#include<iostream>
template<typename Return, typename... Args>
std::ostream& operator <<(std::ostream& os, Return(*p)(Args...) ) {
return os << (void*)p;
}
template <typename ClassType, typename Return, typename... Args>
std::ostream& operator <<(std::ostream& os, Return (ClassType::*p)(Args...) )
{
unsigned char* internal_representation = reinterpret_cast<unsigned char*>(&p);
os << "0x" << std::hex;
for(int i = 0; i < sizeof p; i++) {
os << (int)internal_representation[i];
}
return os;
}
struct test_debugger { void var() {} };
void fun_void_void(){};
void fun_void_double(double d){};
double fun_double_double(double d){return d;}
int main() {
std::cout << "0. " << &test_debugger::var << std::endl;
std::cout << "1. " << fun_void_void << std::endl;
std::cout << "2. " << fun_void_double << std::endl;
std::cout << "3. " << fun_double_double << std::endl;
}
// Prints:
// 0. 0x7018400100000000000
// 1. 0x100401080
// 2. 0x100401087
// 3. 0x100401093
我看到成员函数的地址是0x7018400100000000000
,这是可以理解的,因为成员函数指针有 16 个字节,而自由函数0x100401080
只有 8 个字节。
但是,为什么成员函数地址0x7018400100000000000
离自由函数地址那么远0x100401080
呢?即,|0x7018400100000000000 - 0x100401080| = 0x70184000FFEFFBFEF80
?
为什么它不更接近,例如,0x100401...
而不是0x701840...
?还是我打印的成员函数地址错误?