關於offsetof無法計算動態的數組偏移 error: use of 'this' in a constant expression

用來計算結構體成員的偏移自然我們再熟悉不過,但是對於特殊情況比如

我們也許會在需求中遇到需要計算結構體某個數組成員的某個單元的偏移,那麼這樣的語句是無法通過編譯的

error: use of 'this' in a constant expression

對此我做出的解決方案就是重新實現一個offsetof函數如下

/*
 * 計算offsetof(因爲傳統的offsetof不能加入變量表達式)
 * nsta  : 起始位置
 * ndest : 比較位置
 * 返回值 : 偏移量
 */
int TLR::dynOffsetof(const void *nsta, const void *ndest)
{
    int noffset = 0;
    noffset = static_cast<const char*>(ndest) -
              static_cast<const char*>(nsta);
    return noffset;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章