Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Can virtual inheritance be detected at compile time?
    primarykey
    data
    text
    <p>I would like to determine at compile time if a pointer to Derived can be cast from a pointer to Base without dynamic_cast&lt;>. Is this possible using templates and metaprogramming? This isn't exactly the same problem as determining if Base is a virtual base class of Derived, because Base could be the super class of a virtual base class of Derived.</p> <p>Thanks, Tim Update: I felt good about this method:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Foo { }; class Bar : public Foo { }; class Baz : public virtual Foo { }; class Autre : public virtual Bar { }; typedef char Small; class Big { char dummy[2]; }; template&lt;typename B, typename D&gt; struct is_static_castable { const B* foo; char bar[1]; static Small test(char(*)[sizeof(static_cast&lt;const D*&gt;(foo)) == sizeof(const D*)]); static Big test(...); enum { value = (sizeof(test(&amp;bar)) == sizeof(Small)) }; }; int main() { cout &lt;&lt; "Foo -&gt; Bar: " &lt;&lt; is_static_castable&lt;Foo, Bar&gt;::value &lt;&lt; "\n"; cout &lt;&lt; "Foo -&gt; Baz: " &lt;&lt; is_static_castable&lt;Foo, Baz&gt;::value &lt;&lt; "\n"; cout &lt;&lt; "Foo -&gt; Autre: " &lt;&lt; is_static_castable&lt;Foo, Autre&gt;::value &lt;&lt; "\n"; } </code></pre> <p>But it doesn't work with gcc:</p> <pre><code>multi-fun.cpp: In instantiation of ‘is_static_castable&lt;Foo, Baz&gt;’: multi-fun.cpp:38: instantiated from here multi-fun.cpp:29: error: cannot convert from base ‘Foo’ to derived type ‘Baz’ via virtual base ‘Foo’ multi-fun.cpp:29: error: array bound is not an integer constant multi-fun.cpp: In instantiation of ‘is_static_castable&lt;Foo, Autre&gt;’: multi-fun.cpp:39: instantiated from here multi-fun.cpp:29: error: cannot convert from base ‘Foo’ to derived type ‘Autre’ via virtual base ‘Bar’ multi-fun.cpp:29: error: array bound is not an integer constant </code></pre> <p>Am I confused about what can be done with the sizeof() trick?</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.
 

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