Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have to use <code>static_cast</code>:</p> <pre><code>event_t evt = static_cast&lt;event_t&gt;(&amp;SpecificClass::onBar); </code></pre> <p>This is because it is slightly dangerous to cast to <code>event_t</code>, you could accidently apply it to a <code>BaseClass</code> instance.</p> <p><strong>How it works (for the skeptical):</strong></p> <pre><code>class BaseClass { public: typedef void (BaseClass::*callback_t)(); // callback method void doSomething(callback_t callback) { // some code this-&gt;*callback(); // more code } void baseCallback(); // an example callback }; class DerivedClass : public BaseClass { public: void derivedCallback(); void doWhatever() { // some code doSomething(&amp;BaseClass::baseCallback); // more code doSomething(static_cast&lt;callback_t&gt;(&amp;DerivedClass::derivedCallback)); // et cetera }; </code></pre> <p>Here is what you should <strong>avoid,</strong> and why this is potentially dangerous:</p> <pre><code>void badCodeThatYouShouldNeverWrite() { BaseClass x; // DO NOT DO THIS IT IS BAD x.doSomething(static_cast&lt;callback_t&gt;(&amp;DerivedClass::derivedCallback)); } </code></pre> <p>The requirement for a <code>static_cast</code> makes it so you can't "accidentally" pass <code>DerivedClass</code> method pointers in. And if you think this is dangerous, just remember that it's a pointer, and pointers are always dangerous. Of course, there are ways you can do this that involve creating helper classes, but that requires a lot of extra code (possibly making a class for every function you want to pass as a callback). Or you could use closures in C++11, or something from Boost, but I realize that a lot of us do not have that option.</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. This table or related slice is empty.
    1. 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