简体   繁体   中英

Function as a member “variable” in class

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: eg: 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 a std::function<int(int, int)> and then you can construct Function with a lambda :

#include <functional>
#include <iostream>

class Function {
  std::function<int(int, int)> function;
public:
  Function(std::function<int(int, int)> f) : function(std::move(f)){};
  int calculate(int x, int y){ return function(x, y); }
};

int main() {
  Function divide([](int x, int y){ return x / y; });
  std::cout << divide.calculate(4, 2) << "\n";  
}

Live demo .

But then, as it stands, I'm not sure what Function offers that you can't do with a std::function directly:

#include <functional>
#include <iostream>

using Function = std::function<int(int, int)>;

int main() {
  Function divide([](int x, int y){ return x / y; });
  std::cout << divide(4, 2) << "\n";  
}

Live demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM