I'm new to function pointers and I wrote a small program, where main class use Test class to populate a list with member function pointers. And from my main class I want to call ExeFuns() to call each member function, which I'm not sure how to do. Any help is greatly appreciated. Thanks.
Test.h
Class Test{
public :
void CallFun1();
void CallFun2();
void AddFuns();
void ExeFuns();
};
Test.cpp
std::vector<void (Test::*) ()> callist;
void Test::AddFuns(){
callist.push_back(&Test::CallFun1);
callist.push_back(&Test::CallFun2);
}
void Test::ExeFuns(){
for (int i = 0 ; i<eventlist.size(); i++)
{
callist[i](); // error!
}
}
void Test::CallFun1(){ cout<<"Fun 1"<<endl; }
void Test::CallFun2(){ cout<<"Fun 2"<<endl; }
Main.cpp
main()
{
Test obj;
obj.AddFuns();
obj.ExeFuns();
}
std::function
andstd::bind
. If you don't have C++11, then Boost.Function and Boost.Bind do the same. – Some programmer dudeExeFuns
loop. – Some programmer dude