Reputation: 3
I'm trying to make a class with some member variables that store or point to functions, or can be assigned a different behaviour which describe how to process other variables in the object.
class C {
int n;
void *data;
// buidData: It allocates and stores data using the data pointer avobe to be processed later
// processData: It does something with n and data
public:
void run(); //performs processData
// setters needed...
}
Here, buildData
and processData
could be just methods that do one thing: Maybe buildData
allocates memory for a double and processData
stores n^3 in the allocated position.
What I need for them is to be variables: some function-type variable, or function pointer which can somehow be assigned a code describing its behavior. So, instead of just calculating n^3 always, it could perhaps build a random list of n elements that removes duplicates when the process function is run, store a file name read from console and process a file with that name or... pretty much anything (or nothing at all).
So, in concept, I want empty methods whose behavior I can borrow easily using previously existing code in a parametric fashion.
I strongly feel C++ is giving me the tools to do it (lambda functions, function pointers, the function type in <functional>...
) but for some months I didn't get there yet.
How can I possibly declare buildData
and processData
and how should one assign them their "job" in an elegant way?
Upvotes: 0
Views: 237
Reputation: 13599
Sounds like you are looking for std::function
. You can assign default functions in the same way that you might assign default values to primitive members, but then override the functions in C
's constructor if necessary.
Alternatively, you could go with the classic OOP solution where C
is a base class with default behaviors, but users are allowed to extend into a child class that override
s the behavior for buildData
and processData
.
Upvotes: 3