Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The basic idea is, you define an abstract Callback class, which actually gets passed to your interface. This one calls back to a function passing a single int parameter:</p> <pre><code>struct Callback { virtual ~Callback(){} virtual void operator()(int param)=0; }; </code></pre> <p>This class allows YOUR implementation to be free from knowledge of the code you need to call back into. Of course, to call into a class, you do need an instantiation of Callback that DOES have knowledge of its target. So you then also provide a templated child class that makes it easy for users of your Library to to bind a method in one of their classes to an instance of the generic Callback :-</p> <pre><code>template&lt;class T&gt; class ClassCallback : public Callback { T* _classPtr; typedef void(T::*fncb)(int param); fncb _cbProc; public: ClassCallback(T* classPtr,fncb cbProc):_classPtr(classPtr),_cbProc(cbProc){} virtual void operator()(int param){ (_classPtr-&gt;*_cbProc)(param); } }; </code></pre> <p>To create an instance of the callback from their class, code would look like this. And the invocation is simple too:</p> <pre><code>struct CMyClass { Library* _theLibrary; CMyClass(Library* init):_theLibrary(init){ Callback* pCB = new ClassCallback&lt;CMyClass&gt;(&amp;myClass,&amp;CMyClass::OnCb); _theLibrary-&gt;SetCallback(pCB); } void OnCb(int){ // callback triggered } void Run(){ _theLibrary-&gt;DoWork(); } }; </code></pre> <p>In Summary: Library.h then would look like this. Define the abstract callback class, your library class, and the templated utility class that the customer uses to wrap their their class and its callback method with:</p> <pre><code>// This is the header file what our customer gets struct Callback {... }; class Library { Callback* _pcb; public: void SetCallback(Callback* pcb){_pcb=pcb;} void DoWork(){ int status=0; (*pcb)(status); } ~Library(){delete _pcb;} }; template&lt;class T&gt; struct ClassCallback{ ... }; </code></pre>
 

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