Note that there are some explanatory texts on larger screens.

plurals
  1. POTesting a c++ class for features
    text
    copied!<p>I have a set of classes that describe a set of logical boxes that can hold things and do things to them. I have</p> <pre><code>struct IBox // all boxes do these { .... } struct IBoxCanDoX // the power to do X { void x(); } struct IBoxCanDoY // the power to do Y { void y(); } </code></pre> <p>I wonder what is the 'best' or maybe its just 'favorite' idiom for a client of these classes to deal with these optional capabilities</p> <p>a)</p> <pre><code> if(typeid(box) == typeid(IBoxCanDoX)) { IBoxCanDoX *ix = static_cast&lt;IBoxCanDoX*&gt;(box); ix-&gt;x(); } </code></pre> <p>b)</p> <pre><code> IBoxCanDoX *ix = dynamic_cast&lt;IBoxCanDoX*&gt;(box); if(ix) { ix-&gt;x(); } </code></pre> <p>c) </p> <pre><code>if(box-&gt;canDoX()) { IBoxCanDoX *ix = static_cast&lt;IBoxCanDoX*&gt;(box); ix-&gt;x(); } </code></pre> <p>d) different class struct now</p> <pre><code>struct IBox { void x(); void y(); } ... box-&gt;x(); /// ignored by implementations that dont do x </code></pre> <p>e) same except </p> <pre><code>box-&gt;x() // 'not implemented' exception thrown </code></pre> <p>f) explicit test function</p> <pre><code>if(box-&gt;canDoX()) { box-&gt;x(); } </code></pre> <p>I am sure there are others too.</p> <p>EDIT:</p> <p>Just to make the use case clearer</p> <p>I am exposing this stuff to end users via interactive ui. They can type 'make box do X'. I need to know if box can do x. Or I need to disable the 'make current box do X' command</p> <p>EDIT2: Thx to all answerers</p> <p>as Noah Roberts pointed out (a) doesnt work (explains some of my issues !). I ended up doing (b) and a slight variant</p> <pre><code> template&lt;class T&gt; T* GetCurrentBox() { if (!current_box) throw "current box not set"; T* ret = dynamic_cast&lt;T*&gt;(current_box); if(!ret) throw "current box doesnt support requested operation"; return ret; } ... IBoxCanDoX *ix = GetCurrentBox&lt;IBoxCanDoX&gt;(); ix-&gt;x(); </code></pre> <p>and let the UI plumbing deal nicely with the exceptions (I am not really throwing naked strings). </p> <p>I also intend to explore Visitor</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