I'm trying to implement an array of member function pointers in a class. I've googled around, and this is what I've come up with. Its not working and giving me all sorts of errors.
A non-static member function pointer can't be called in the usual way. You've got to tell it which object to use.
In particular, the left of the function-call operator has to be a pending member-function invocation - a special kind of expression using the operators .* or ->* like this:
1 2 3 4 5 6 7 8
void MyClass::emote(){
(this->*react[SCREAM])();
(this->*react[WHISPER])();
// or through an object:
MyClass& x = *this;
(x.*react[SLEEP])();
}
In your particular case, you might as well make your functions static, in which case you can treat them just like normal function pointers:
You place the type of the function to be called (note: not the type of the pointer-to-function) in the angle brackets. In other words, you write std::function< return_type(parameter_type_1, parameter_type_2, ..., parameter_type_n) >
For instance, to create a std::function that targets the function f():
int f(char a, double b);
Which returns int and accepts two parameters of types char and double:
std::function< int(char, double) > g = f;
If the function being targeted is a member function, the std::function needs to take a pointer or reference (or some other related things) to the object as its first parameter. This is because member functions take a pointer to the object to be called as the first argument, called the implicit object argument. So given bool MyClass::scream(string s), the associated function object needs to have the type
1 2
std::function< bool(MyClass*, string) > f = &MyClass::scream; // or
std::function< bool(MyClass&, string) > g = &MyClass::scream;
Thank you for the explanation. The static method worked fine, but when I started using it in my real program I was running into problems with static functions calling non-static functions.
This way works fine. I really appreciate the help.
I working on porting a paint program I wrote in java, to Qt in C++. Ill post a link to github when I get a little further along. Each of those emotes above are really different types of drawing tools in my real program.
Your help is in the mycanvas.h. Right now there are only two mouse functions - draw ( not implemented yet) and drag.
So far I know there's a huge memory leak in the MyCanvas::paintEvent override. But I can't figure it out. I'm deleting the only new object at the end of the function.