Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ Callback -- How to decouple the call back type
    primarykey
    data
    text
    <p>For example, in the following pseudo code, Class B need to call A::Action() through B::m_cb member.<br><br> The objective is, how to make a general, non-template Callback class, so "B" does not have to be a template, and the "CallBack" can hold any kind of function signature.<br> <br>I ever use such code before, but now I can not find that implementation. All I remember is:<br> - the "CallBack" itself is not a template, but it contains member template<br> - the helper function template make_callback will instantiate CallBack object<br></p> <p>Can anyone give a poiinter?</p> <pre><code>Class A { public: void Action(){//...}; }; class CallBack { //... // CallBack it self it is a NOT a template // It can wrap member template though }; class B { public: void SetCallback(CallBack to){ m_cb = to; } void do_something() { //... m_cb.Execute(); //... } private: CallBack m_cb; }; int main() { A obj1; CallBack cb = make_callback(&amp;obj1, &amp;A::Action); B obj2; obj2.SetCallback(cb); //.... obj2.do_something(); } </code></pre> <p>Here is the sample code I got from this same website. I tried to improved it a little bit, so it can tolerate arbitrary call back function's return type. But it still can not handle arbitrary number of arguments, like in line 18. Also, , T is the pointer to member function, which should be depend on C. I don't know how to enforce this.</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; // INTERNAL CLASSES class CallbackSpecBase { public: virtual ~CallbackSpecBase() {} virtual void operator()(...) const = 0; }; template&lt;class C, class T&gt; class CallbackSpec : public CallbackSpecBase { public: CallbackSpec(C&amp; o, T m) : obj(o), method(m) {} /*line 18*/ void operator()(...) const { (&amp;obj-&gt;*method)(); } // how to pass "..." into method(...) private: C&amp; obj; T method; }; // PUBLIC API class Callback { public: Callback() {} void operator()() { (*spec)(); } template&lt;class C, class T&gt; void set(C&amp; o, T m) { spec.reset(new CallbackSpec&lt;C, T&gt;(o, m)); } private: std::auto_ptr&lt;CallbackSpecBase&gt; spec; }; // TEST CODE class Test { public: void foo() { std::cout &lt;&lt; "Working" &lt;&lt; std::endl; } void bar() { std::cout &lt;&lt; "Like a charm" &lt;&lt; std::endl; } }; int main() { Test t; Callback c; c.set(t, &amp;Test::foo); c(); c.set(t, &amp;Test::bar); c(); } </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.
 

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