用来计算结构体成员的偏移自然我们再熟悉不过,但是对于特殊情况比如
我们也许会在需求中遇到需要计算结构体某个数组成员的某个单元的偏移,那么这样的语句是无法通过编译的
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;
}