关于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;
}

 

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