Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Fact 1: The expression <code>&amp;Type::member</code> has type <code>MemberType ClassType::*</code>, where <code>ClassType</code> is the class where <code>member</code> is declared, not necessarily <code>Type</code>.</p> <p>Fact 2: It is legal (though not always safe) to <code>static_cast</code> a reference or pointer from a base class to a derived class only if the base class is not a virtual base (nor an ambiguous base). It seems to me that this is exactly the things you want to check at every use of <code>GetObjectFromMember</code>.</p> <p>So how about:</p> <pre><code>// Precondition: mptr points at the specified member of a ClassType object. // Precondition: member must not be in a virtual base class of ClassType. // // The second precondition is not an issue if the template arguments are // deduced from an &amp;AnyClass::member expression, since ClassType will // deduce as the member's actual enclosing class. template&lt;typename ClassType, typename MemberType&gt; ClassType* ObjectContainingMember(MemberType ClassType::*member, MemberType *mptr) { ClassType* dummy = 0; std::size_t member_offset = reinterpret_cast&lt;char*&gt;(&amp;(dummy-&gt;*member)) - reinterpret_cast&lt;char*&gt;(dummy); char* obj_addr = reinterpret_cast&lt;char*&gt;(mptr) - member_offset; return reinterpret_cast&lt;ClassType*&gt;(obj_addr); } // Precondition: MemberPointer points at the specified member of // an ObjectType object. Returns a pointer to that ObjectType. #define GetObjectFromMember(ObjectType,MemberName,MemberPointer) \ static_cast&lt;ObjectType*&gt;(ObjectContainingMember( \ &amp;ObjectType::MemberName, MemberPointer)) </code></pre> <p>Because of fact 1, the template parameter <code>ClassType</code> will be deduced as the class where the member is declared.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload