开发者

presentation and usage of functionality at runtime

开发者 https://www.devze.com 2023-02-07 03:08 出处:网络
I want to present a class\'s functionalities(member functions) to outside world without exposing it\'s functions in it\'s public section. so the user will be able to know/invoke it\'s functions dynam

I want to present a class's functionalities(member functions) to outside world without exposing it's functions in it's public section. so the user will be able to know/invoke it's functions dynamically. Here are some methods:

a) Provide pointers to member functions. pointers which are served in structs with an accompanying string to hold the name of the function.

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消