【问题标题】:Assess position of member at compile time在编译时评估成员的位置
【发布时间】:2016-04-26 09:09:18
【问题描述】:

考虑以下示例:

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 中的位置。

【问题讨论】:

    标签: c++ pointers compile-time


    【解决方案1】:

    您可以使用offsetof macro

    size_t constexpr b_offset = offsetof(mystruct, b);
    

    请注意,您不能在同一个类定义中的函数之外使用offsetof,因为这个类还不完整。

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2017-12-22
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      相关资源
      最近更新 更多