类模版std::function
是一种通用、多态的函数封装。std::function
的实例可以对任何可以调用的目标实体进行存储、复制、和调用操作,这些目标实体包括普通函数、Lambda表达式、函数指针、以及其它函数对象等。std::function
对象是对C++中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的)。
通常std::function是一个函数对象类,它包装其它任意的函数对象,被包装的函数对象具有类型为T1, …,TN的N个参数,并且返回一个可转换到R类型的值。std::function
使用 模板转换构造函数接收被包装的函数对象;特别是,闭包类型可以隐式地转换为std::function
。
- #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;
- }
对于各个可调用实体转换成std::function
类型的对象,上面的代码都有,运行一下代码,阅读一下上面那段简单的代码。总结了简单的用法以后,来看看一些需要注意的事项:
- 关于可调用实体转换为
std::function
对象需要遵守以下两条原则:- 转换后的
std::function
对象的参数能转换为可调用实体的参数; - 可调用实体的返回值能转换为
std::function
对象的返回值。
- 转换后的
std::function
对象最大的用处就是在实现函数回调,使用者需要注意,它不能被用来检查相等或者不相等,但是可以与NULL或者nullptr进行比较。
为什么要用std::function
好用并实用的东西才会加入标准的。因为好用,实用,我们才在项目中使用它。std::function
实现了一套类型消除机制,可以统一处理不同的函数对象类型。以前我们使用函数指针来完成这些;现在我们可以使用更安全的std::function
来完成这些任务。
还有为什么?我也不知道还有为什么?等以后发现了更好的实际应用实例再回来说为什么吧。
总结
C++11的加入,貌似让C++变了一个语言似的,也有了Lambda表达式,好多东西都要去学习,好多新的语言特性。哦,慢慢来吧。