title: C++ Compile-Time offsetof inside a template
body: <p>I have the need to use <code>offsetof</code> from a <code>template</code> with a member selector. I've come up with a way, if you'll excuse the awkward syntax:</p>
  
  <pre><code>template &lt;typename T,
            typename R,
            R T::*M
           &gt;
  constexpr std::size_t offset_of()
  {
      return reinterpret_cast&lt;std::size_t&gt;(&amp;(((T*)0)-&gt;*M));
  };
  </code></pre>
  
  <p>Usage isn't perfect (annoying at best):</p>
  
  <pre><code>struct S
  {
      int x;
      int y;
  };
  
  static_assert(offset_of&lt;S, int, &amp;S::x&gt;() == 0, "");
  static_assert(offset_of&lt;S, int, &amp;S::y&gt;() == sizeof(int), "");
  </code></pre>
  
  <p>The non-<code>constexpr</code> form is easier to use:</p>
  
  <pre><code>template &lt;typename T, typename R&gt;
  std::size_t offset_of(R T::*M)
  {
      return reinterpret_cast&lt;std::size_t&gt;(&amp;(((T*)0)-&gt;*M));
  };
  </code></pre>
  
  <p>at the obvious disadvantage that it isn't done at compile-time (but easier to use):</p>
  
  <pre><code>int main()
  {
      std::cout &lt;&lt; offset_of(&amp;S::x) &lt;&lt; std::endl;
      std::cout &lt;&lt; offset_of(&amp;S::y) &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>What I'm looking for is syntax <em>like</em> the non-<code>constexpr</code> variety, but still fully compile-time; however, I can't come up with the syntax for it. I would also be happy with an <code>offset_of&lt;&amp;S::x&gt;::value</code> (like the rest of the type traits), but can't figure out the syntax magic for it.</p>