I assume your requirement is more complicated than your example because you don't need function pointers to solve it as written.
You can have a simple function pointer to a free function or a static member function. Simple function pointers cannot reference a member function because they lack the "this" pointer to the instance of the object.
There are several approaches to this. One is in the TR1 extensions to the C++ library:
#include <tr1/functional>
int C::Fun(int i){
std::tr1::function<int(int,int)> pFun;
if(i==1)
pFun = std::tr1::bind(&C::First,
this,
std::tr1::placeholders::_1,
std::tr1::placeholders::_2);
else
pFun = std::tr1::bind(&C::Second,
this,
std::tr1::placeholders::_1,
std::tr1::placeholders::_2);
return pFun(1,2);
}
#include <tr1/functional>
int C::Fun(int i){
std::tr1::function<int(int,int)> pFun;
if(i==1)
pFun = std::tr1::bind(&C::First,
this,
std::tr1::placeholders::_1,
std::tr1::placeholders::_2);
else
pFun = std::tr1::bind(&C::Second,
this,
std::tr1::placeholders::_1,
std::tr1::placeholders::_2);
return pFun(1,2);
}
To copy to clipboard, switch view to plain text mode
Bookmarks