im bit new c++, please let me describe problem. have class called csubcriber, main purpose execute callback function, of type , number of arguments. example callbacks can be:
typedef void (*cb1)(void) typedef int (*cb2)(int, int) typedef char (*cb3)(int, int, void);
class is:
template <class callbacktype> class csubscriber { public: csubscriber(); virtual ~csubscriber(); callbacktype (*m_callback_newway)(void *params); void (*m_callback)(void *params); int (*m_callback_int)(void *params); void *m_cb_params; int execute_cb(); void *m_params; csubscriber(void (*callback)(void *params), void *cb_params); csubscriber(int (*callback)(void *params), void *cb_params); }; csubscriber::csubscriber(void (*callback)(void *params), void *cb_params){ m_callback = callback; m_cb_params = cb_params; } csubscriber::csubscriber(int (*callback)(void *params), void *cb_params){ m_callback_int = callback; m_cb_params = cb_params; }
my main problem now, how write constructor, handle variable arguments callback. after constructing object in particular moment, callback may fired, example:
typedef int (*callback)(void *params); csubscriber s(callback, params);
or
typedef void (*callback2)(void *params, int arr, char *ptr); csubscriber s(callback, params, arr, ptr);
now, calling
s->m_callback()
i want execute callback arguments passed constructor. i'd avoid writing ten different constructors, each different number of arguments passed callback function. possible ?
try this.
#include <iostream> using namespace std; typedef void (*cb1)(void); typedef int (*cb2)(int, int); typedef char (*cb3)(int, int, char); template <class callbacktype> class csubscriber { public: csubscriber(): fcn1(0), fcn2(0), fcn3(0) {}; virtual ~csubscriber(){}; csubscriber(cb1 fcn): fcn1(fcn), fcn2(0), fcn3(0), a(), b() {}; csubscriber(cb2 fcn, int p1, int p2): fcn1(0), fcn2(fcn), fcn3(0), a(p1), b(p2) {}; int execute_cb() { if ( fcn1 != 0 ) { (*fcn1)(); } if ( fcn2 != 0 ) { (*fcn2)(a,b); } }; protected: cb1 fcn1; cb2 fcn2; cb3 fcn3; int a, b; }; void fcn1() { cout << "in fcn1" << endl; }; int fcn2(int a, int b) { cout << "in fcn2, " << << ", b " << b << endl; }; int main() { csubscriber<int> cs; csubscriber<int> cs1(&fcn1); csubscriber<int> cs2(&fcn2, 1, 100); cs.execute_cb(); cs1.execute_cb(); cs2.execute_cb(); }
Comments
Post a Comment