![](/img/trans.png)
[英]C++ rookie: how can I store code for a class in helper/auxiliary files, but still access all class member functions?
[英]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;
簡短的答案,這是將函數指針存儲在數組中的示例。 注意未編譯。
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};
}
最好的選擇是查看我在此處放置的鏈接。 它深入研究了語法。 如果您使用的是新的C ++ 11,則可以使用std :: function,或者如果您具有boost,則可以使用boost :: function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.