title: C++ callback using class member
body: <p>I know this has been asked so many times, and because of that it's difficult to dig through the cruft and find a simple example of what works.</p>
  
  <p>I've got this, it's simple and it works for <code>MyClass</code>...</p>
  
  <pre><code>#include &lt;iostream&gt;
  using std::cout;
  using std::endl;
  
  class MyClass
  {
      public:
          MyClass();
          static void Callback(MyClass* instance, int x);
      private:
          int private_x;
  };
  
  class EventHandler
  {
      public:
          void addHandler(MyClass* owner)
          {
              cout &lt;&lt; "Handler added..." &lt;&lt; endl;
              //Let's pretend an event just occured
              owner-&gt;Callback(owner,1);
          }
  };
  
  EventHandler* handler;
  
  MyClass::MyClass()
  {
      private_x = 5;
      handler-&gt;addHandler(this);
  }
  
  void MyClass::Callback(MyClass* instance, int x)
  {
      cout &lt;&lt; x + instance-&gt;private_x &lt;&lt; endl;
  }
  
  int main(int argc, char** argv)
  {
      handler = new EventHandler();
      MyClass* myClass = new MyClass();
  }
  
  class YourClass
  {
      public:
          YourClass();
          static void Callback(YourClass* instance, int x);
  };
  </code></pre>
  
  <p>How can that be rewritten so <code>EventHandler::addHandler()</code> will work with both <code>MyClass</code> and <code>YourClass</code>. I'm sorry but it's just the way my brain works, I need to see a simple example of what works before I can comprehend why/how it works. If you've got a favorite way to make this work now's the time to show it off, please markup that code and post it back.</p>
  
  <p><strong>[edit]</strong></p>
  
  <p>It was answered but the answer was deleted before I could give the checkmark.
  The answer in my case was a templated function. Changed addHandler to this...</p>
  
  <pre><code>class EventHandler
  {
      public:
          template&lt;typename T&gt;
          void addHandler(T* owner)
          {
              cout &lt;&lt; "Handler added..." &lt;&lt; endl;
              //Let's pretend an event just occured
              owner-&gt;Callback(owner,1);
          }
  };
  </code></pre>