2016-04-26 46 views
0

考虑下面的例子:在编译时评估构件的位置

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_cast s至确定构件b的位置在存储器中的结构mystruct内。在我的系统上(并且,我猜,在任何合理的系统上),上面的收益率为4

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

回答

2

你可以做到这一点与offsetof macro

size_t constexpr b_offset = offsetof(mystruct, b); 

注意,你不能使用offsetof之外的功能相同的类定义,因为这个类是不完整呢。