我将如何存储类的成员函数

How would I store member functions of a class?

本文关键字:成员 函数 存储 何存储      更新时间:2023-10-16

我想知道我是否可以,传入一个类实例的指针,获取它的成员函数并将其存储在列表中。我该怎么做?

简单的方法是使用一些模板魔术和继承:

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);
};

然后 main() 函数看起来像:

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();
}

一旦你想要存储一个类的所有成员函数,你需要几个向量:

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

长答案,这是教程页面中函数指针C++教程教程

简短的回答,下面是在数组中存储函数指针的示例。注意未编译。

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 
}

现在成员函数的语法略有不同:

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};
}

您最好的选择是查看我在此处放置的链接。它深入研究了sytax等等。如果您使用的是新的 C++11,那么您可以使用 std::function,或者如果您有 boost,则可以使用 boost::function。