I am looking to make a class in C++ which can have a changeable function as one of its individual properties. Is there any standard way to achieve this? What would the syntax look like?
For example, something I have tried and want to do:
#include <iostream>
class Thing {
private:
int val;
void func();
public:
Thing(int val = 0) {
this->val = val;
}
void setFunc(void func()) { this->func() = func; }
void useFunc() { this->func(); }
};
int main() {
Thing thing1 = Thing(1);
thing1.setFunc({
std::cout << "i am thing 1, my value is: " << this->val;
});
thing1.useFunc();
return 0;
}
I'm not sure what the syntax would be like for something like this, or if pointers are needed. This (probably obviously) returns a couple of errors, those being:
./main.cpp:16:46: error: expression is not assignable
void setFunc(void func()) { this->func() = func; }
~~~~~~~~~~~~ ^
./main.cpp:28:51: error: invalid use of 'this' outside of a non-static member function
std::cout << "i am thing 1, my value is: " << this->val;
^
I realize I could use a lot of properties that aren't functions instead, then have one method which uses these properties to determine the outcome, however I am not looking to do this, as it would require a lot more properties and I want to try something different for the sake of learning how to do it. In this example there'd be no point in doing what I am trying to do, but this is just an example.