函数对象及Lambda

Callable Object(可被调用对象)

可被某种方式调用某些函数的对象

  • 一个函数,接受额外传入的args作为参数(argument)
  • 一个指向成员函数的指针,当通过对象调用时该对象被传递为第一实参(必须为reference或pointer),其他实参对应成员函数的参数
  • 一个函数对象(function object,拥有operator()),附带的args被传递作为实参
  • 一个lambda(本质为函数对象)
    示例如下:
void func(int x, int y);
auto lam = [](int x, int y) {
  ...
};

class C {
 public:
  void operator() (int x, int y) const;
  void memfunc(int x, int y) const;
};

int main() {
  C c_obj;
  std::shared_ptr<C> sp(new C);

  //bind() use callable objects to bind arguments
  std::bind(func, 77, 33)(); //普通函数
  std::bind(lam, 77, 33)();  //lambda
  std::bind(C(),77, 33);     //C::operator()(77,33)
  std::bind(&C::memfunc, c_obj, 77,33);//c_obj.operator()(77, 33)
  std::bind(&C::memfunc, sp,77,33); //sp->memfunc(77,33)

  //async异步调用
  std::async(func, 77, 33);
  std::async(lam, 77, 33);
  std::async(c_obj, 77, 33);//c_obj.operator()(77, 33)
  std::async(&C::memfunc, &c_obj, 77, 33);//c_obj.memfunc(77,33)
  std::async(&C::memfunc, sp, 77, 33);//sp->memfunc(77,33)
}

Function Type Wrapper(外覆器)

Class std::function<>于<functional>
e.g

void func(int x, int y);

//initialize collections of tasks
std::vector<std::function<void(int, int)>> tasks;
tasks.push_back(func);
tasks.push_back([](int x, int y) {
                  ....
                });
//call each task
for(std::function<void(int, int)> f : tasks) {
  f(33, 66);
}

//使用成员函数()
class C {
 public: 
  void memfunc(int x, inty) const;
};
std::function<void(const C&, int, int)> mf;
mf =  &C::memfunc;
mf(C(), 42, 77);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值