I know that one cannot cast a non-static member function to a void *.
(http://users.utu.fi/sisasa/oasis/cpp...o-members.html)
However, I have a case where I need to call a certain member function
based on a value passed into another function.
Since there are a large number of these values and therefore a large
number of potential functions I need to call, I wanted to avoid using a
massive switch statement (or equivalently, if/elseif) and to store these
functions in an efficient data structure so I can extract the member
function to call based on the value and then call it.
Now, I come up with a design that I believe will work and would be
perfectly legal, but I wanted to check with some of the fine folks here
just to make sure.
class CAClass;
typedef long (CAClass::*CAClassFunction)( /*params*/ );
class CAFunc
{
CAFunc( CAClass *obj, CAClassFunction func );
~ CAFunc( void ) {}
long Call( /*params*/ ) { return (mObj->*mFunc)( /*params*/ ); }
protected:
CAClass *mObj;
CAClassFunction mFunc;
private:
};
class CFuncs
{
public:
CFuncs( void );
virtual ~ CFuncs( void );
virtual void AddFunc( const long key, void *func );
virtual void *GetFunc( const long key );
protected:
/* storage var here */
private:
};
class CAClass
{
public:
virtual long RandomMemberFunc( /*params*/ );
protected:
CFuncs mTheFuncs;
};
So, inside of an instance of CAClass, I should be able to do:
// Add a member func
mThefuncs.
AddFunc( uniqueKey,
new CAFunc( this, &CAFunc::RandomMemberFunc ) );
// Get and call member func
CAFunc *func = (CAFunc*)mTheFuncs.GetFunc( uniqueKey );
if ( func )
returnValue = func->Call( /*params*/ );
I've left out various details, but nothing that should be vital.
So, everything look legal?
Assuming it is legal, out of curiosity, Would you consider such a thing
just a "bad idea" and use the massive switch statement anyway?
--