简体   繁体   English

作为班上“变量”成员

[英]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. 因此,我研究了void (*foo)(int)方法。 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: 答案:@Chris Drew指出:
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;}); 当然,您的Function可以存储std::function<int(int, int)> ,然后可以使用lambda构造Function :例如: 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 . 但是然后我不确定您的Function提供了什么,您不能只使用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 : 当然,您的Function可以存储std::function<int(int, int)> ,然后可以使用lambda构造Function

#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: 但是,就目前情况而言,我不确定是什么Function可以直接使用std::function做不到的:

#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 . 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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