std::function以及std::bind

转自:https://blog.csdn.net/shuilan0066/article/details/82788954

示例1 : 普通函数
void gFunc()
{
    cout << "gFunc" << endl;
}
int main()
{
    std::function<void()> f = gFunc;
    f();
    getchar();
    return 0;
}
 
 

 

示例2 模板函数

template <class T>
T g_Add(T i, T j)
{
  cout << i + j;
  return i + j;
}


int main()
{
  std::function<int(int,int)> f = g_Add<int>;
  f(2,3);

  getchar();
  return 0;
}
 

 

示例三: 匿名函数

auto g_Lambda = [](int i, int j)
{
  return i + j;
}; //匿名函数 此处有分号

int main()
{
  std::function<int(int, int)> f = g_Lambda;
  cout<<f(2,3);

  getchar();
  return 0;
}

 

示例四:函数对象

/函数对象
struct Add
{
  int operator()(int i, int j)
  {
    return i + j;
  }
};

//模板函数对象
template <class T>
struct AddT
{
  T operator()(T i, T j)
  {
    return i + j;
  }
};


int main()
{
  std::function<int(int, int)> f = Add();
  cout<<f(2,3)<<endl;

  std::function<int(int, int)> ft = AddT<int>();
  cout << ft(5, 6)<<endl;

  getchar();
  return 0;
}
 

 

示例5:类成员函数

class Computer
{
  public:
  static int Add(int i, int j)
  {
    return i + j;
  }

  template<class T>
  static T AddT(T i, T j)
  {
    return i + j;
  }

  int AddN(int i, int j)
  {
    return i + j;
  }
};

//存储对成员函数的调用 

int main()
{
  //1、 类静态函数
  std::function<int(int, int)> f = &Computer::Add;
  cout << f(1, 1) << endl;

  //2、 类静态模板函数
  std::function<int(int, int)> ft = &Computer::AddT<int>;
  cout << ft(1, 1) << endl;



  //普通函数绑定 需要构造类对象
  Computer c;

  //3、 普通函数 需使用bind,将类对象地址 &c 绑定上
  std::function<int(int, int)> fN = std::bind(&Computer::AddN, &c, placeholders::_1, placeholders::_2);
  cout << fN(1, 1) << endl;

  //4、普通函数, 也可以这样调用 个人觉得这个比 bind 麻烦,不建议
  std::function <int(const Computer &, int, int)> fN2 = &Computer::AddN;
  cout << fN2(c,1, 1) << endl;

  getchar();
  return 0;
}

 

转载于:https://www.cnblogs.com/judes/p/11205819.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值