就在这个问题因重复而被驳回之前,大多数(如果不是全部)问题都已接受答案,并带有过时/未定义的行为解决方案。
有没有办法在编译时获得指向成员数据的指针的偏移量:
nullptr事物)gcc trunk在编译器资源管理器中)offsetof(或类似地,就像提议的代码一样)。使用 GCC 的主干版本,以下技巧(hack)不起作用:
#include <cstdint>
#include <cstddef>
namespace detail
{
// The union stuff is for CLang to avoid creating warnings
template<typename T, auto MPtr>
struct offsetof_ptr_helper
{
union helper_t { int i = 0; T value; };
static constexpr helper_t v = {};
static constexpr size_t sz = sizeof
(uint8_t[
(uint8_t *)&(v.value.*MPtr) -
(uint8_t *)&v.value
]);
};
} …Run Code Online (Sandbox Code Playgroud) c++ ×1