I briefly started converting the methods to static methods that passed in the object this in as the first parameter before I stepped back and looked at the problem properly. Function pointers to class methods are a part of the C++ standard. It required a very light touch to get the code to compile correctly. Here is a stolen code sample illustrating pointers to methods. I have modified it slightly to include a typedef for the method pointer.
As ever I stand back staggered by what is out there on the internet. Wikipedia has an excellent section on function pointers here - and amazingly there is/was a site http://www.function-pointer.org/ dedicated to explanations of function pointers.
class Adder
{
int x;
public:
Adder(int in) : x(in) { }
int addx(int y) { return x + y; }
// declare MethodPointer
typedef int (Adder::*MethodPointer)(int);
};
int main()
{
// pointer to the addx method
Adder::MethodPointer new_function
= &Adder::addx;
// Create an Adder instance
Adder foo = Adder(3);
// Call the method
std::cout << (foo.*new_function)(5)
<< std::endl; // prints "8"
return 0;
}
No comments:
Post a Comment