我将如何存储类的成员函数
How would I store member functions of a class?
我想知道我是否可以,传入一个类实例的指针,获取它的成员函数并将其存储在列表中。我该怎么做?
简单的方法是使用一些模板魔术和继承:
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。
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法