Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Why using a template?</p> <pre><code>#include &lt;cstdio&gt; struct Foo { int a; int b; } foo = {2, 3}; int const (Foo::*mp) = &amp;Foo::b; int main() { printf("%d\n", foo.*mp); return 0; } </code></pre> <p>The following compiles <code>mp</code> to this on gcc-4.4.1 (I don't have access to MSVC at the moment):</p> <pre><code>.globl mp .align 4 .type mp, @object .size mp, 4 mp: .long 4 </code></pre> <p>It is just an offset to the member, which looks pretty compile-time to me.</p> <p>With template, you need to specify the definition outside of the class:</p> <pre><code>#include &lt;cstdio&gt; struct Foo { int m; int r; } foo = {2, 3}; template&lt;int Foo::*Mem&gt; struct B { static int Foo::* const mp; }; template&lt;int Foo::*Mem&gt; int Foo::* const B&lt;Mem&gt;::mp = Mem; int main() { typedef B&lt;&amp;Foo::m&gt; Bm; typedef B&lt;&amp;Foo::r&gt; Br; printf("%d, %d\n", foo.*(Bm::mp), foo.*(Br::mp)); } </code></pre> <p>Which compiles to:</p> <pre><code>g++ -O2 -S -o- b.cc | c++filt ... .weak B&lt;&amp;(Foo::r)&gt;::mp .section .rodata._ZN1BIXadL_ZN3Foo1rEEEE2mpE,"aG",@progbits,B&lt;&amp;(Foo::r)&gt;::mp,comdat .align 4 .type B&lt;&amp;(Foo::r)&gt;::mp, @object .size B&lt;&amp;(Foo::r)&gt;::mp, 4 B&lt;&amp;(Foo::r)&gt;::mp: .long 4 .weak B&lt;&amp;(Foo::m)&gt;::mp .section .rodata._ZN1BIXadL_ZN3Foo1mEEEE2mpE,"aG",@progbits,B&lt;&amp;(Foo::m)&gt;::mp,comdat .align 4 .type B&lt;&amp;(Foo::m)&gt;::mp, @object .size B&lt;&amp;(Foo::m)&gt;::mp, 4 B&lt;&amp;(Foo::m)&gt;::mp: .zero 4 </code></pre> <p>However this all smacks of standard library features reimplementation (see <code>std::tr1::mem_fn</code>).</p>
 

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