在编译时评估成员的位置

Assess position of member at compile time

考虑以下示例:

struct mystruct
{
    int a;
    int b;
    int c;
};

int main()
{
    mystruct x;

    std :: cout << reinterpret_cast <size_t> (&(x.b)) - reinterpret_cast <size_t> (&x) << std :: endl;
}

上面所做的是使用reinterpret_casts 来确定成员b 在结构mystruct 中的内存中的位置。在我的系统上(我猜,在任何合理的系统上)上面的结果是 4

现在,我需要做的是完全相同,但在编译时。有没有办法完成这样的事情?我需要的是一些 static constexpr size_t 在编译时会告诉我 bmystruct.

中的位置

你可以用 offsetof macro:

size_t constexpr b_offset = offsetof(mystruct, b);

请注意,您不能在同一 class 定义中的函数之外使用 offsetof,因为此 class 尚未完成。