I was thinking about how to improve my simple calculator using some advanced techniques. I came to question, is there some way to create a class with function you could define per instance:
class Function
{
public:
Function(function);
~Function();
private:
function;
};
So for example you create an instance
Function divide(int x / int y); //For example
I hope you understand the question.
EDIT:
So I studied the void (*foo)(int)
method. It could be used. But the initial idea was to create a generic function that holds the function itself in it. Not just a pointer to a function defined outside. So you could do something like this:
int main() {
//Define the functions
Function divide( X / Y ); //Divide
Function sum( X + Y ); //Sum
//Ask the user what function to call and ask him to enter variables x and y
//User chooses divide and enters x, y
cout << divide.calculate(x, y) << endl;
return 0;
}
Answer:
@Chris Drew pointed out:
Sure, your Function
can store a std::function<int(int, int)>
and then you can construct Function
with a lambda: e.g: Function divide([](int x,int y){return x / y;});
But then I'm not sure what your Function
offers that you can't just do with std::function
.
It answers my question, unfortunately my question was put on hold so I cannot mark the question resolved.
Sure, your
Function
can store astd::function<int(int, int)>
and then you can constructFunction
with a lambda:Live demo.
But then, as it stands, I'm not sure what
Function
offers that you can't do with astd::function
directly:Live demo.