Better way to call member function using function pointer?
Hi,
Following is isolated code reproducing the issue I encountered while
using function pointers:
//////////////////////////////////////////////
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Sample
{
public:
Sample()
{
funPtrs["fun1"] = &Sample::fun1;
funPtrs["fun2"] = &Sample::fun2;
funPtrs["fun3"] = &Sample::fun3;
}
void process()
{
string str[] = { "fun1", "fun2", "fun3" };
// Method 1 - Compilation error.
for (int i = 0; i < 3; ++i)
{
// VS 2005 gives me error as:
// error C2064: term does not evaluate to a function taking 1
arguments
funPtrs[str[i]]("hi");
}
// Method 2 - Works fine.
for (int i = 0; i < 3; ++i)
{
ptr = funPtrs[str[i]];
(this->*ptr)("hello");
}
}
private:
void fun1(string str)
{
str = "fun1";
cout << str << endl;
}
void fun2(string str)
{
str = "fun2";
cout << str << endl;
}
void fun3(string str)
{
str = "fun3";
cout << str << endl;
}
private:
static map<string, void (Sample::*)(string)> funPtrs;
void (Sample::*ptr)(string);
};
map<string, void (Sample::*)(string)> Sample::funPtrs;
int main()
{
Sample s;
s.process();
return 0;
}
//////////////////////////////////////////////
To my understanding Method 1 gives error because function is called
using pointer which is not a member of Sample, due to which "this"
cannot be passed to the member function as argument. Hence the
mentioned error.
Adding a pointer as member variable specifically to make the function
calls, works fine (Method 2). I was wondering if this is the only way
to do it or there exist a better method/design to achieve this.
Regards,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]