std::function
在c++98&03时我们通常使用回调函数来处理一些需要某种场景下才触发的回调操作,但回调函数有一个限制就是它只能赋值给同类型的全局或者静态函数,对于其他有相同的返回值和相同类型参数的成员函数不能赋值。
- #include <iostream>
- using namespace std;
- //define a callback func
- typedef void(*CALL_BACK)(void);
- //global func
- void show(void)
- {
- cout << "show global func" << endl;
- }
- class A
- {
- public:
- //member func
- void show_class_num(void ){ cout << "show member func" << endl; }
- //static member func
- static void show_class_num_static(void ){ cout << "show static member func" << endl; }
- };
- int main()
- {
- CALL_BACK call;
- //assign a global func to callback func
- call = show;
- call();
- //error
- call = A::show_class_num;
- //assign a static member func
- call = A::show_class_num_static;
- call();
- return 0;
- }
- // 仿函数(functor)
- class Functor
- {
- public:
- int operator()(int a)
- {
- return a;
- }
- }
C++11中引入了std::funtion这个模板类,这个模板类是一个多用途的函数包裹器,std::function的实例可以存储,拷贝和调用任何的可调用实体,包括全局函数,成员函数,lambda表达式和仿函数以及std::bind绑定的对象,甚至是成员变量,std::function统一和简化了相同类型可调用实体的使用方式,使得编码变得更简单。
std::function的原型:
template< class R, class... Args >
class function<R(Args...)>
R是返回值类型,Args是函数的参数类型,实例一个std::function对象很简单,就是将可调用对象的返回值类型和参数类型作为模板参数传递给std::function模板类。比如:
std::function<void()> f1;
std::function<int (int , int)> f2;
std::function的使用
- #include <iostream>
- #include <functional>
- using namespace std;
- std::function<int(void)> func;
- int testFunc()
- {
- cout << "global Func" << endl;
- return 0;
- }
- auto lambda = [](void) -> int {cout << "lambda func" << endl; return 0; };
- class Func
- {
- int operator()(void)
- {
- cout << "仿函数" << endl;
- return 0;
- }
- };
- class CFuntion
- {
- public:
- int ClassMember(){ cout << "class member function" << endl; return 0; }
- int static StaticClassFunc(){ cout << "static class member function" << endl; return 0; }
- };
- int main()
- {
- func = testFunc;
- func();
- func = lambda;
- func();
- func = CFuntion::StaticClassFunc;
- func();
- CFuntion classFunc;
- func = std::bind(&CFuntion::ClassMember, classFunc);
- func();
- return 0;
- }