有两种方法可以创建仿函数(一个保存状态的函数):
绑定(bind)一个函数并定义一个状态:
bind(f, _1, state)
双 g(双 x,双状态){ 返回x+状态; } function f = bind(g,_1,state);
使用
()
运算符和一个类:
struct f {
double state;
f(double state_):state(state_) {}
double operator()(double x) {return x+state;}
};
我发现 bind
-method 写起来更快,但我想知道是否有一些隐藏的石头,因为在文献中的大部分时间我都将仿函数视为类的 ()
运算符。
最佳答案
3.方式是lambda表达式:
auto f = [state]( double x ) { return x * state; };
关于performance - 类的 operator() 或将函数绑定(bind)为仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18169838/