简体   繁体   中英

How would I store member functions of a class?

I want to know if I could, pass in a pointer of an instance of a class, get it's member functions and store it in a list. How would I do that?

Easy way is with some template magic and inheritance:

template<class R>
class Base {
public:
   virtual R Execute() const=0;
};

template<class R, class P1, class P2>
class Derived : public Base<R> { 
public:
   void set_params(P1 p1, P2 p2) { m_p1 = p1; m_p2 = p2; }
   R Execute() const { return Map(m_p1,m_p2); }
protected:
   virtual R Map(P1, P2) const=0;
private:
  P1 m_p1;
  P2 m_p2;
};

template<class T, class R, class P1, class P2>
class MemFunc : public Derived<R,P1,P2> {
public:
   MemFunc(T *object, R (T::*fptr)(P1, P2)) : object(object), fptr(fptr) { }
   virtual R Map(P1 p1, P2 p2) const { return (object->*fptr)(p1,p2); }
private:
   T *object;
   R (T::*fptr)(P1,P2);
};

And then main() function would look like:

int main() {
   std::vector<Base<int>*> vec;
   Object o;
   Derived<int, float,float> *ptr = new MemFunc(&o, &Object::MyFunc);
   ptr->set_params(10.0,20.0);
   vec.push_back(ptr);
   int i = vec[0].Execute();
}

Once you want all member functions of a class stored, you need several vectors:

std::vector<Base<int>*> vec_int;
std::vector<Base<float>*> vec_float;
std::vector<Base<MyObject>*> vec_myobject;

Long answer, here is a tutorial for function pointers in C++ tutorial page

Short answer, here is a example of storing a function pointer in an array. Note not compiled.

typedef void(*pFunc)(void); //pFunc is an alias for the function pointer type
void foo1(){};
void foo2(){}
int main(){
  pFunc funcs[2] = {&foo1, &foo2}; //hold an array of functions 
}

Now member function is a little different syntax:

struct Foo{
  void foo1(){}
  void foo2(){}
}

typedef (*Foo::pFunc)(); //pFunc is an alias to member function pointer

int main(){
  pFunc funcs[2] = {&Foo::foo1, &Foo::foo2};
}

Your best bet is to check out the link I placed here. It delves into the sytax and more. If you are using the new C++11, then you may utilize std::function, or if you have boost, you can use boost::function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM