类的operator()或绑定函数作为函子? [英] Class's operator() or bind a function as a functor?

查看:268
本文介绍了类的operator()或绑定函数作为函子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以创建一个函数(一个保存状态的函数):

There are two ways to make a functor (a function that holds a state):


  1. 绑定函数并定义一个状态: bind(f,_1,state)

double g(double x,double state){
return x + state;
}
function f = bind(g,_1,state);

double g(double x, double state) { return x+state; } function f = bind(g,_1,state);

use code>运算符和类:

use () operator and a class:





struct f { 
  double state; 
  f(double state_):state(state_) {} 
  double operator()(double x) {return x+state;}
};

我发现 bind 写作,但我想知道是否有一些隐藏的石头,因为大多数时间在文学中我看到函子作为类的()运算符。

I find that bind-method is faster to write but I'm wondering if there are some hidden stones since most of the time in literature I see functor as class's () operator.

推荐答案

3.方式是一个lambda表达式:

The 3. way is a lambda expression:

auto f = [state]( double x ) { return x * state; };

这篇关于类的operator()或绑定函数作为函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆