Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Massive Edit</strong></p> <p>I think I got what you want, based on some heavy type-casting.</p> <p>Note that I do <strong>NOT</strong> recommend this technique. Although my example works, I believe there are some big pitfalls here that could really screw things up.</p> <p>As before, Class <code>A</code> can accept both a method of the proper signature and an object (of type <code>B</code>, or derived from type <code>B</code>, such as your <code>C</code> classes), and call the specified method on the specified object.</p> <p>Class <code>B</code> does not actually have any methods at all, and only acts as a common base-class for the two classes <code>C1</code> &amp; <code>C2</code>.</p> <p>At the bottom is a <code>main</code> that demonstrates how this is used. I left out the implementation of the two <code>SetCallback***</code> methods, as they're trivial.</p> <pre><code>class B { public: // Has nothing, only serves as base-class for C1 and C2. }; class C1: public B { public: bool DoThis(int x) const { return true; } }; class C2: public B { public: bool DoThat(int x) const { return false; } }; class A { private: bool (B::*m_check)(int) const; B* m_Obj; public: void SetCallbackFunction(bool (B::*fnc)(int) const) { m_check = fnc; } void SetCallbackObject(B* pB) { m_Obj = pB; } bool InvokeCallback(int val) { return (m_Obj-&gt;*m_check)(val); } }; int _tmain(int argc, _TCHAR* argv[]) { A a; C1 c; bool (C1::*func)(int) const; bool (B::*b_func)(int) const; func = &amp;C1::DoThis; b_func = (bool (B::*)(int) const)(func); // Dangerous Typecasting. Use caution! a.SetCallbackFunction(b_func); a.SetCallbackObject((B*)(&amp;c)); // A simpler, safer typecast. a.InvokeCallback(5); // Ends up calling C1::DoThis. _getch(); return 0; } </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.
 

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