View Full Version : How to call a class member function via function pointer in map [C++]

07-06-2009, 05:47 AM
I'm trying to declare a std::map that is keyed by a char and has a function pointer as a second parameter, these functions would be a member function of my class. But for some odd reason I cannot call the functions when extracted...

So, I have a class A as shown below, it contains a map as well as a function

class A
map<char, void (A::*)(void)> mapA;
void func();

Next I have main code that looks like this:

A::A() // constructor
// Generate User Options
mapA['a'] = &A::func;

Now, I try to execute func by extracting it from the map and running the function:

map<char, void (A::*)(void)>::iterator it;
for ( it=mapA.begin() ; it != mapA.end(); it++ )

I would assume this would launch function "func" as it is stored in the map, but instead it generates the following error message:
error C2064: term does not evaluate to a function taking 0 arguments

Any help would be greatly appreciated...

ralph l mayo
07-07-2009, 01:46 AM
That error message isn't very helpful.

The problem is that, while you can store pointers to member functions in variables, if you want to call them again you must have an instance of the class they are defined in handy to use with them, otherwise if they used 'this' or accessed any other member data the behavior would be undefined, because there wouldn't be any.

So, use static functions if you can, and if you can't do that try storing objects that define an operator() instead of functions. If you can't do that either you'll need some ugly syntax like (some_instance_of_A.*(it->second))

Short example of the options:

class Test
void bar() { std::cout << "bar"; }
static void baz() { std::cout << "baz"; }
void operator()() { std::cout << "foo"; }

int main()
Test a;
void (Test::*member)() = &Test::bar;

//member(); // error: must use ‘.*’ or ‘->*’ to call pointer-to-member function

(a.*member)(); // Works fine with a specific instance. A bit ugly, though

void (*staticfn)() = &Test::baz;
staticfn(); // Fine, static members don't need context

a(); // Fine, obviously. functionoid-style call

C++ faq lite on the subject, highly recommended (http://www.parashift.com/c++-faq-lite/pointers-to-members.html)