可调用对象包装器
std::function是可调用对象的包装器。它是一个类模板,可以容纳除了类成员(函数)指针之外的所有可调用对象。通过指定它的模板参数,它可以用统一的方式处理函数,函数对象,函数指针,并允许保存和延迟执行它们。
基本用法:
std::function必须要包含一个叫做functional的头文件,可调用对象包装器使用语法如下:
#include <functional>
std::function<返回值类型(参数类型列表)> diy_name = 可调用对象;
1.包装普通函数
2.包装类的静态函数
3.包装仿函数
4.包装转换成函数指针的对象
代码如下:
#include <iostream>
#include <functional>
#include <string>
using namespace std;void print(int num, string name)
{cout << "id = "<<name << ",age = " << num << endl;
}using funcptr = void(*)(int, string);class Test
{
public:static void world(int a, string s){cout << "number = " << a << ",name = " << s << endl;}void operator()(string msg){cout << "仿函数:" << msg << endl;}operator funcptr(){return world;}
};int main()
{//1.包装普通函数function<void(int, string)> f1 = print;//2.包装类的静态方法function<void(int, string)> f2 = Test::world;//3.包装仿函数Test ta;function<void(string)> f3 = ta;//4.包装转换成函数指针的对象Test tb;function<void(int, string)> f4 = tb;//调用f1(1, "ace");f2(2, "tom");f3("jack");f4(3, "lily");return 0;
}
测试结果:
代码如下:
#include <iostream>
#include <functional>
#include <string>
using namespace std;class A
{
public:A(const function<void(int, string)> &f) :callback(f){}void notify(int id, string name){callback(id, name);}private:function<void(int, string)> callback;
};void print(int num, string name)
{cout << "id = " << name << ",age = " << num << endl;
}using funcptr = void(*)(int, string);class Test
{
public:static void world(int a, string s){cout << "number = " << a << ",name = " << s << endl;}void operator()(string msg){cout << "仿函数:" << msg << endl;}operator funcptr(){return world;}
};int main()
{//1.包装普通函数function<void(int, string)> f1 = print;//2.包装类的静态方法function<void(int, string)> f2 = Test::world;//3.包装仿函数Test ta;function<void(string)> f3 = ta;//4.包装转换成函数指针的对象Test tb;function<void(int, string)> f4 = tb;A aa(print);aa.notify(1, "tom");A ab(Test::world);ab.notify(2, "jack");A ac(tb);ac.notify(3, "luf");return 0;
}
测试结果: