I will do my best to explain this as clearly as possible.
My example currently involves 3 different classes.
- My model class (lets call it
MyModel.cpp) - My data class that MyModel has an object of (
MyData.cpp) - My undo redo class that modifies my model (
MyModelUR.cpp)
MyModel has a MyData object. MyData contains a bunch of doubles each with its own get and set function. The way my system works is the setter is called by calling redo() in MyModelUR. This redo() function is called in MyModel when a change is detected. This is outside the scope of the problem though.
MyModelUR has 3 functions, a constructor which takes a few args, undo() and redo() which are NOT allowed to take any args.
What happens is, I want MyModel to pass a function pointer of the desired setter in MyData to MyModelUR.
So, that means the constructor for MyModelUR needs to take a function pointer as an arg and then store it in a private global variable. So far I have something like this…
MyModelUR::MyModelUR(MyModel* model, double newValue, void (*function)(double))
{
Model = model;
NewValue = newValue;
//FunctionToCall is a void*
FunctionToCall = &function;
}
Now, in my redo() function, I want to use FunctionToCall…I’m trying to do this but it’s not working and just giving me compiling errors…
MyModelUR::redo()
{
Model->data()->FunctionToCall(NewValue);
}
I want to implement it this way so I don’t need X number of undo()/redo() functions for each double in MyData.
I appreciate your help and suggestions, but I have a few restrictions when considering replies like, I want to use this architecture due to some other constraints I have, and I can’t use Boost libraries.
TLDR; I want to call a void function pointer which takes a double in a separate class that’s being called on an object.
Thank you!
EDIT: After the comments below this is what I’m working with…
MyModelUR::MyModelUR(MyModel* model, double newValue, void (MyModel::*function)(double)) :
Model(model),
NewValue(newValue),
FunctionToCall(function)
{
}
void MyModelUR::redo()
{
MyData data = Model->data();
data.*FunctionToCall(NewValue);
}
However, this throws the error on the 2nd line of code in redo() that says: “must use ‘.‘ or ‘->‘ to call pointer-to-member function in …”
Firstly, your function pointer should be a method pointer, and you’re trying to use a free-function pointer.
Secondly, don’t try to store this as a
void*, it isn’t guaranteed to be the same size. Just declare it as a method pointer and stop casting.Lastly, you’re currently storing (in your
void*) the address of the transient function pointer argument, which will be invalid even if it were the right type.Your code should end up something like this:
Instantiate one of these like:
Functional note: you’ll need a getter method pointer and somewhere to store the old value as well, if you want undo.
Aesthetic note: initial uppercase member names are horrible, it’s the same scheme you’re using for types. Just IMO.