2016-04-26 95 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之外的功能相同的類定義,因爲這個類是不完整呢。