I know how to make a function an input argument when the function isn't a method, but I can't figure out how to do it when the function is a method.
Here's what I tried:
#include <iostream>
class A
{
void funct_1(int a, void (A::*f)(int))
{
(A::*f)(a);
}
public:
void funct_2(int k)
{
// do something
}
void funct_3(int k)
{
// do something
}
void funct_4(int k)
{
// some reason to use the function argument functionality...
if (k % 2)
funct_1(k, funct_2);
else
funct_1(k, funct_3);
}
};
int main()
{
A a;
a.funct_4(4);
return 0;
}
The above code doesn't compile. I've tried lots of variations, but can't find any syntax use that works. Could someone explain what I'm doing wrong here in terms of the syntax?
The pointer to member syntax is always hard to figure out. You are always there, just change the first member function to
void funct_1(int a, void (A::*f)(int))
{
(this->*f)(a);
}
and the fourth to
void funct_4(int k)
{
if (k % 2)
funct_1(k, &A::funct_2);
else
funct_1(k, &A::funct_3);
}
For you original attempt to call the member function, note that (A::*f)(a);
is conceptually wrong, as it doesn't associate the member function pointer f
with an instance of A
. Member function pointers are offsets into a class definition, but not tight to a particular instance of that class. This must be provided when doing the actual call. Specific operator exist to do exactly that, i.e. .*
and ->*
as in this->*f
. As their precedence is low, you need to add an additional set of parentheses: (this->*f)
.