2016-04-07 11 views
1

こんにちは、私はそれが逆のためにクラスのメンバーのオフセットを計算するために(C++によって)標準であるかどうかを調べようとしています。それはparent_pnullptrであると&(parent_p->*offset)を行うには法的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; 
} 

ですか?

答えて

2

明らかな結果がなく、しばらく議論されています。しかし、実装が提供する標準的な祝福を受けたoffsetofマクロでは、この議論は意味がありません。

関連する問題