title: Obtaining a pointer-to-member from addresses of an object and its member
body: <p>I'm looking to reverse the <code>.*</code> operator. </p>
  
  <p>When I have a pointer I can dereference it with <code>*</code> and then from dereferenced value go back to the pointer by <code>&amp;</code> operator. </p>
  
  <p>With pointer-to-member I can dereference it with <code>.*</code> operator (supplying the object instance)  but there is no operator to obtain the original pointer-to-member from object and its dereferenced field.</p>
  
  <p>Consider the following data structure:</p>
  
  <pre><code>struct Point { double x, y, z; };
  </code></pre>
  
  <p>Now I need to get a pointer to member <code>double Point::*</code> from <code>(Point&amp;, double&amp;)</code> pair, where that <code>double &amp;</code> is a field of the <code>Point&amp;</code> object.</p>
  
  <p>In other words I need a function <code>to_member_ptr</code> such that:</p>
  
  <pre><code>template&lt;typename DataType, typename Member&gt;
  constexpr Member DataType::* obtain_member_ptr(const DataType &amp;that, const Member &amp;fieldInThat);
  
  int main(int, char*[]) {
      Point pt;
      static_assert(obtain_member_ptr(pt, pt.x) == &amp;Point::x, "error");
      static_assert(obtain_member_ptr(pt, pt.y) == &amp;Point::y, "error");
      static_assert(obtain_member_ptr(pt, pt.z) == &amp;Point::z, "error");
  }
  </code></pre>
  
  <p>I could write it by hand for given datatype as below:</p>
  
  <pre><code>constexpr double Point::* obtain_member_ptr(const Point &amp;that, const double &amp;fieldInThat)     {
      if(&amp;that.x == &amp;fieldInThat) return &amp;Point::x;
      if(&amp;that.y == &amp;fieldInThat) return &amp;Point::y;
      if(&amp;that.z == &amp;fieldInThat) return &amp;Point::z;
      return nullptr;
  }
  </code></pre>
  
  <p>But it seems like a plain boilerplate and I feel that there should be a way to make compiler do that for me.</p>
  
  <p>How can I portably obtain a pointer to object from object and its field?</p>