Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This answer is based off <a href="https://stackoverflow.com/questions/75538/hidden-features-of-c/2176229#2176229">this fun-fact</a>: In a function returning <code>void</code>, you can return any expression of which the type is void.</p> <p>So the simple solution is:</p> <pre><code>virtual T Execute() const { if (comm) // boolean logic change, typo in OP? return comm(); else return static_cast&lt;T&gt;(NULL); } </code></pre> <p>When <code>T = void</code>, the last return statement is equivalent to <code>return;</code>.</p> <hr> <p>However, I feel this is bad design. Is <code>NULL</code> meaningful for <em>every</em> <code>T</code>? I don't think so. I would throw an exception:</p> <pre><code>virtual T Execute() const { if (comm) return comm(); else throw std::runtime_error("No function!") } </code></pre> <p>However, this is done <a href="http://www.boost.org/doc/libs/1_43_0/doc/html/boost/bad_function_call.html" rel="nofollow noreferrer">automatically by Boost</a>, so your code becomes the much cleaner:</p> <pre><code>virtual T Execute() const { return comm(); } </code></pre> <p>You could then add additional functionality, such as:</p> <pre><code>bool empty(void) const { return !comm; // or return comm.empty() if you're the explicit type } </code></pre> <p>So the user can check if it can be called prior to calling it. Of course at this point, unless your class has additional functionality you've left out for the sake of the question, I see no reason not to just use <code>boost::function</code> in the first place.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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