Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: <a href="http://en.cppreference.com/w/cpp/utility/functional/function"><code>std::function</code></a> and <a href="http://en.cppreference.com/w/cpp/utility/functional/bind"><code>std::bind</code></a>:</p> <pre><code>#include &lt;functional&gt; class EventHandler { public: void addHandler(std::function&lt;void(int)&gt; callback) { cout &lt;&lt; "Handler added..." &lt;&lt; endl; // Let's pretend an event just occured callback(1); } }; </code></pre> <p>The <code>addHandler</code> method now accepts a <code>std::function</code> argument, and this "function object" have no return value and takes an integer as argument.</p> <p>To bind it to a specific function, you use <code>std::bind</code>:</p> <pre><code>class MyClass { public: MyClass(); // Note: No longer marked `static`, and only takes the actual argument void Callback(int x); private: int private_x; }; MyClass::MyClass() { using namespace std::placeholders; // for `_1` private_x = 5; handler-&gt;addHandler(std::bind(&amp;MyClass::Callback, this, _1)); } void MyClass::Callback(int x) { // No longer needs an explicit `instance` argument, // as `this` is set up properly cout &lt;&lt; x + private_x &lt;&lt; endl; } </code></pre> <p>You need to use <code>std::bind</code> when adding the handler, as you explicitly needs to specify the otherwise implicit <code>this</code> pointer as an argument. If you have a free-standing function, you don't have to use <code>std::bind</code>:</p> <pre><code>void freeStandingCallback(int x) { // ... } int main() { // ... handler-&gt;addHandler(freeStandingCallback); } </code></pre> <p>Having the event handler use <code>std::function</code> objects, also makes it possible to use the new C++11 <a href="http://en.wikipedia.org/wiki/C++11#Lambda_functions_and_expressions">lambda functions</a>:</p> <pre><code>handler-&gt;addHandler([](int x) { std::cout &lt;&lt; "x is " &lt;&lt; x &lt;&lt; '\n'; }); </code></pre>
    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