2016-04-07 44 views
1

嗨我想弄清楚是否合法(由C++)標準來計算類的成員的偏移量(爲了扭轉它)。反轉數據成員指針

class A 
{ 
public: 
    int a, b, c, d; 
}; 

template <typename ParentClass, typename T> 
ParentClass const * offset_this_pointer(T const * member_ptr, T ParentClass::* offset) 
{ 
    ParentClass const * parent_p = nullptr; 
    // we are technically dereferencing a NULL pointer here, 
    // but we are not using the result, only taking the address of it 
    // This works and yields the desired result in MSVC 2010, gcc 4.9.2 and Solaris10 compilers. 
    T const * offset_p = &(parent_p->*offset); 

    return reinterpret_cast<ParentClass const *>((uintptr_t)member_ptr - (uintptr_t)(offset_p)); 
} 

int main() 
{ 
    A a; 

    assert(&a == offset_this_pointer(&a.b, &A::b)); // passes 

    return 0; 
} 

是否合法C++做&(parent_p->*offset)parent_p是一個nullptr

回答

2

這個問題已經有一段時間了,沒有明顯的結果。然而,辯論與實施提供的,標準祝福的宏觀offsetof無關。