Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's possible with C++11 and <code>decltype</code>. For that, we'll exploit that a pointer-to-member is not a pointer into the derived class when the member is inherited from a base class.</p> <p>For example:</p> <pre><code>struct base{ void f(){} }; struct derived : base{}; </code></pre> <p>The type of <code>&amp;derived::f</code> will be <code>void (base::*)()</code>, not <code>void (derived::*)()</code>. This was already true in C++03, but it was impossible to get the base class type without actually specifying it. With <code>decltype</code>, it's easy and only needs this little function:</p> <pre><code>// unimplemented to make sure it's only used // in unevaluated contexts (sizeof, decltype, alignof) template&lt;class T, class U&gt; T base_of(U T::*); </code></pre> <p>Usage:</p> <pre><code>#include &lt;iostream&gt; // unimplemented to make sure it's only used // in unevaluated contexts (sizeof, decltype, alignof) template&lt;class T, class R&gt; T base_of(R T::*); struct base{ void f(){} void name(){ std::cout &lt;&lt; "base::name()\n"; } }; struct derived : base{ void name(){ std::cout &lt;&lt; "derived::name()\n"; } }; struct not_deducible : base{ void f(){} void name(){ std::cout &lt;&lt; "not_deducible::name()\n"; } }; int main(){ decltype(base_of(&amp;derived::f)) a; decltype(base_of(&amp;base::f)) b; decltype(base_of(&amp;not_deducible::f)) c; a.name(); b.name(); c.name(); } </code></pre> <p>Output:</p> <pre><code>base::name() base::name() not_deducible::name() </code></pre> <p>As the last example shows, you need to use a member that is actually an inherited member of the base class you're interested in.</p> <p>There are more flaws, however: The member must also be unambiguously identify a base class member:</p> <pre><code>struct base2{ void f(){} }; struct not_deducible2 : base, base2{}; int main(){ decltype(base_of(&amp;not_deducible2::f)) x; // error: 'f' is ambiguous } </code></pre> <p>That's the best you can get though, without compiler support.</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