It seems like you're confused about how member function pointers work. For a given class, there is only a single instance of any given function. They are differentiated by the use of the implicit parameter this
. Basically, you can pretend you have the following mapping.
struct Struct { void Function(); }
Struct a;
a.Function();
turns into
struct Struct { }
void Function(Struct* this);
Struct a;
Function(&a);
So if you have a bunch of Struct
objects, and you want to call Function
on a small set of them, you don't store Function
, you store Struct
.
Pointers to member functions are used when you have multiple functions, that you want to call selectively. So if you have two functions in your class, both of which take no paramters and return void, void (Struct::*)()
can point to either of them. But it still points to a specific function, of which there's only one. You still need to provide the this
parameter.
struct Struct {
Struct(int v) : value(v) { }
void One() { cout << "one: " << value << endl; }
void Two() { cout << "two: " << value << endl; }
int value;
};
int main()
{
std::vector<Struct> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
std::vector<void (Struct::*)()> f;
f.push_back(&Struct::One);
f.push_back(&Struct::Two);
f.push_back(&Struct::One);
for(int i = 0; i < 3; ++i)
(v[i].*f[i])();
}
Not the best example, but it gets the point across. You can mix and match objects, with member functions.
*edit: An example without containers getting in the way
Struct a(5), b(10);
void (Struct::*one)() = &Struct::One;
void (Struct::*two)() = &Struct::Two;
(a.*one)();
(b.*one)();
(a.*two)();
(b.*two)();
Note the extra parenthesis. a.*one()
is insufficient.