class IBase
{
public:
typedef void (IBase::*FuncPtr)(Iparameter*);
typedef struct Module
{
FuncPtr Func;
string Name;
};
vector<Module> GetFunctions()const
{
vector<Module>开发者_如何学Python vec;
vec.push_back(Module(&F1, "F1"));
vec.push_back(Module(&F2,"F2"));
return vec;
}
private:
void F1(IParameter *param){}
void F2(IParameter *param){}
};
b) Provide a string list of function names, plus, a function taking a string parameter to invoke specified member function.
class IBase
{
public:
void Invoke(string funcName, IParameter *param)
{
if(funcName=="F1")F1(param);
else if(funcName=="F2")F2(param);
}
private:
void F1(IParameter *param){}
void F2(IParameter *param){}
};
Question: which method is more efficient? are there any better approaches? am I re-inventing the wheel(boost::function? )?
Notes:
* IParameter is such a class that is, designed to hold generic/self-explanatory data and each function knows how to interpret it. * All functions' signature are the same:void FuncName(IParameter*);
Thanks
Well, quicker than linearly searching through a vector or a series of if-else
would be to use e.g. a std::map
(O(log N) lookup time), or a std::hash_map
(O(1) lookup time typically).
But the real question is: why do you want to access functions by name (i.e. with a string) at run-time? Surely an index or a pointer would be easier? In other words, why is the first argument to your Invoke()
function a string?
精彩评论