Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The best solution, use <code>boost::function</code> with <code>boost::bind</code>, or if your compiler supports tr1/c++0x use <code>std::tr1::function</code> and <code>std::tr1::bind</code>.</p> <p>So it becomes as simple as:</p> <pre><code>boost::function&lt;void()&gt; callback; Target myTarget; callback=boost::bind(&amp;Target::doSomething,&amp;myTarget); callback(); // calls the function </code></pre> <p>And your set callback becomes:</p> <pre><code>class MyClassWithCallback{ public: void setCallback(boost::function&lt;void()&gt; const &amp;cb) { callback_ = cb; } void call_it() { callback_(); } private: boost::function&lt;void()&gt; callback_; }; </code></pre> <p>Otherwise you need to implement some abstract class</p> <pre><code>struct callback { virtual void call() = 0; virtual ~callback() {} }; struct TargetCallback { virtual void call() { ((*self).*member)()); } void (Target::*member)(); Target *self; TargetCallback(void (Target::*m)(),Target *p) : member(m), self(p) {} }; </code></pre> <p>And then use:</p> <pre><code>myCaller.setCallback(new TargetCallback(&amp;Target::doSomething,&amp;myTarget)); </code></pre> <p>When your class get modified into:</p> <pre><code>class MyClassWithCallback{ public: void setCallback(callback *cb) { callback_.reset(cb); } void call_it() { callback_-&gt;call(); } private: std::auto_ptr&lt;callback&gt; callback_; }; </code></pre> <p>And of course if the function you want to call does not change you may just implement some interface, i.e. derive Target from some abstract class with this call.</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