这是一个完全符合标准的实现,用于显示指向成员的指针的内存表示:
#include <iostream>
#include <iomanip>
template<int... I> struct index_tuple { using succ = index_tuple<I..., sizeof...(I)>; };
template<int I> struct indexer { using type = typename indexer<I - 1>::type::succ; };
template<> struct indexer<0> { using type = index_tuple<>; };
template<typename T> typename indexer<sizeof(T)>::type index(const T &) { return {}; }
template<typename T> class dumper {
unsigned char buf[sizeof(T)];
friend std::ostream &operator<<(std::ostream &os, const dumper &o) {
std::ios_base::fmtflags flags{os.flags()};
std::copy_n(o.buf, sizeof(T),
std::ostream_iterator<int>(os << std::hex << std::showbase, " "));
return os << std::setiosflags(flags);
}
template<int... I> dumper (const T &t, index_tuple<I...>):
buf{reinterpret_cast<const unsigned char *>(&t)[I]...} {}
public:
dumper(const T &t): dumper(t, index(t)) {}
};
template<typename T> dumper<T> dump(const T &t) { return {t}; }
struct ManyIntegers {
int a,b,c,d;
};
int main () {
std::cout << "p = &ManyIntegers::a = " << dump(&ManyIntegers::a) << std::endl;
std::cout << "p = &ManyIntegers::b = " << dump(&ManyIntegers::b) << std::endl;
std::cout << "p = &ManyIntegers::c = " << dump(&ManyIntegers::c) << std::endl;
std::cout << "p = &ManyIntegers::d = " << dump(&ManyIntegers::d) << std::endl;
}
输出如预期:
p = &ManyIntegers::a = 0 0 0 0
p = &ManyIntegers::b = 0x4 0 0 0
p = &ManyIntegers::c = 0x8 0 0 0
p = &ManyIntegers::d = 0xc 0 0 0