当前位置:首页 > 通信资讯 > 正文

c++ std function(c++11 std::function)

目录
  • 一、介绍
  • 二、实例
  • 三、与std::bind的区别
  • 总结

一、介绍

std::function是函数模板类(是一个类)。包含在#include <functional> 中。以前没有这个类的时候,我们在想定义一个回调函数指针,非常的麻烦。我们通常这样的定义:

?
1 typedef void(*ptr)(intint// 这里的ptr就是一个函数指针

而使用了std::function这个类的时候,我们可以这样使用,来替换函数指针。例如:

?
1 std::function<void(int ,int)> func;

std::function 的实例能存储、复制及调用任何可调用 (Callable) 目标——函数、 lambda 表达式、 bind 表达式或其他函数对象,还有指向成员函数指针和指向数据成员指针。

它也是对 C++ 中现有的可调用实体的一种类型安全的包裹(相对来说,函数指针的调用不是类型安全的)

二、实例

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 #include <iostream> #include <vector> #include <list> #include <map> #include <set> #include <string> #include <algorithm> #include <functional> #include <memory> using namespace std; //声明一个模板 typedef std::function<int(int)> Functional; //normal function int TestFunc(int a) { return a; } //lambda expression auto lambda = [](int a)->int{return a;}; //functor仿函数 class Functor { public: int operator() (int a) { return a; } }; //类的成员函数和类的静态成员函数 class CTest { public: int Func(int a) { return a; } static int SFunc(int a) { return a; } }; int main(int argc, char* argv[]) { //封装普通函数 Functional obj = TestFunc; int res = obj(0); cout << "normal function : " << res << endl; //封装lambda表达式 obj = lambda; res = obj(1); cout << "lambda expression : " << res << endl; //封装仿函数 Functor functorObj; obj = functorObj; res = obj(2); cout << "functor : " << res << endl; //封装类的成员函数和static成员函数 CTest t; obj = std::bind(&CTest::Func, &t, std::placeholders::_1); res = obj(3); cout << "member function : " << res << endl; obj = CTest::SFunc; res = obj(4); cout << "static member function : " << res << endl; return 0; }

运行结果

c++ std function(c++11 std::function)

三、与std::bind的区别

可将std::bind函数看作一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。

std::bind将可调用对象与其参数一起进行绑定,绑定后的结果可以使用std::function保存。std::bind主要有以下两个作用:

  • 将可调用对象和其参数绑定成一个仿函数;
  • 只绑定部分参数,减少可调用对象传入的参数。
?
1 2 3 4 5 6 7 double my_divide(double x, double y) { return x / y; }; int main(int argc, char* argv[]) { auto fn_half = std::bind(my_divide, std::placeholders::_1, 2); std::cout << fn_half(10) << '\n'; // 输出为5 return 0; }

参考:

C++ std::function的用法详解

C++11 中的std::function和std::bind详解

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/sinat_31608641/article/details/120692268

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。