title: Callback in C++, template member? (2)
body: <p>The following callback class is a generic wrapper to "callable things". I really like its API, which has no templates and is very clean, but under the hood there is some dynamic allocation which I was not able to avoid.</p>
  
  <p>Is there any way to get rid of the <strong>new</strong> and <strong>delete</strong> in the code below while maintaining the semantics and API of the callback class? I really wish I could.</p>
  
  <hr>
  
  <p><strong>Needed stuff:</strong></p>
  
  <pre><code>// base class for something we can "call"
  class callable {
    public:
    virtual void operator()() = 0;
    virtual ~callable() {}
  };
  
  // wraps pointer-to-members
  template&lt;class C&gt;
  class callable_from_object : public callable {
    public:
    callable_from_object(C&amp; object, void (C::*method)())
           : o(object), m(method) {}
  
    void operator()() {
      (&amp;o -&gt;* m) ();
    }
    private:
    C&amp; o;
    void (C::*m)();
  };
  
  // wraps pointer-to-functions or pointer-to-static-members
  class callable_from_function : public callable {
     public:
     callable_from_function(void (*function)())
           : f(function) {}
  
     void operator()() {
        f();
     };
     private:
     void (*f)();
  };
  </code></pre>
  
  <hr>
  
  <p><strong>The callback class:</strong></p>
  
  <pre><code>// generic wrapper for any callable
  // this is the only class which is exposed to the user
  class callback : public callable {
     public:
     template&lt;class C&gt;
     callback(C&amp; object, void (C::*method)())
           : c(*new callable_from_object&lt;C&gt;(object, method)) {}
     explicit callback(void (*function)())
           : c(*new callable_from_function(function)) {}
     void operator()() {
        c();
     }
     ~callback() {
        std::cout &lt;&lt; "dtor\n"; // check for mem leak
        delete &amp;c;
     }
     private:
     callable&amp; c;
  };
  </code></pre>
  
  <hr>
  
  <p><strong>An API example:</strong></p>
  
  <pre><code>struct X {
    void y() { std::cout &lt;&lt; "y\n"; }
    static void z() { std::cout &lt;&lt; "z\n"; }
  } x;
  
  void w() { std::cout &lt;&lt; "w\n"; }
  
  int main(int, char*[]) {
     callback c1(x, &amp;X::y);
     callback c2(X::z);
     callback c3(w);
     c1();
     c2();
     c3();
     return 0;
  }
  </code></pre>
  
  <hr>
  
  <p>Thanks a lot !! :-)</p>