标签:ons const print include 对象 tor stream divide when
语义:
类模板std::function是可调用对象的包装器,可以包装除了类成员之外的所有可调用对象。包括,普通函数,函数指针,lambda,仿函数。通过指定的模板参数,它可以用统一的方式保存,并延迟执行它们。所谓的延迟执行,就是回调了。
它使得C++对C的兼容性更强了。
常规多态案例:
#include <iostream>
#include <functional>
using namespace std;
class Operator
{
public:
virtual int op(int,int) = 0;
};
class OperatorAdd:public Operator
{
public:
int op(int i,int j)
{
return i+j;
}
};
class OperatorMinus:public Operator
{
public:
int op(int i,int j)
{
return i-j;
}
};
int main()
{
Operator *oper = new OperatorAdd;
cout<<oper->op(4,5)<<endl;
oper = new OperatorMinus;
cout<<oper->op(10,4)<<endl;
return 0;
}
多态转std::function
#include <iostream>
#include <functional>
#include <map>
using namespace std;
int add(int i,int j)
{
return i+j;
}
int _minus(int i,int j)
{
return i-j;
}
typedef int(*MINUS)(int,int);
//using MINUS = int(*)(int,int)
auto multiply = [](int i,int j){return i*j;};
class Divide
{
public:
int operator()(int i, int j){
return i/j;
}
};
int main()
{
std::function<int(int,int)> oper;
oper = add;
cout<<oper(1,2)<<endl;
MINUS m = _minus;
oper = m;
cout<<oper(10,1)<<endl;
oper = multiply;
cout<<oper(1,2)<<endl;
oper = Divide();
cout<<oper(10,2)<<endl;
map<string,std::function<int(int,int)>> math;
math.insert({"+",add});
math.insert({"-",_minus});
math.insert({"*",multiply});
math.insert({"/",Divide()});
math.insert({"%",[](int i, int j){return i%j;}});
cout<<math["+"](10,5)<<endl;
cout<<math["-"](10,5)<<endl;
cout<<math["*"](10,5)<<endl;
cout<<math["/"](10,5)<<endl;
cout<<math["%"](10,5)<<endl;
return 0;
}
写完这段代码完全被震撼了,被感动的不要不要的。C++的灵活性简直逆天了。
应用:
常规回调
#include <iostream>
#include <functional>
using namespace std;
class functor
{
public:
void operator()()
{
cout<<__FUNCTION__<<endl;
}
};
class A
{
public:
A(const function<void()> & cb):_callback(cb)
{}
void notify()
{
_callback();
}
function<void()> _callback;
};
int main(int argc, char *argv[])
{
functor fct;
A a(fct);
a.notify();
return 0;
}
#include <iostream>
#include <functional>
using namespace std;
void printWhenEven(int data,const std::function<void(int)> &f)
{
if(data%2)
f(data);
}
void print(int i)
{
cout<<i<<endl;
}
int main()
{
for(int i =0;i<10;i++)
{
printWhenEven(i,print);
cout<<"+++++++++++++++++++"<<endl;
// printWhenEven(i,[](int i){cout<<i+1<<endl;});
}
}
标签:ons const print include 对象 tor stream divide when
原文地址:https://www.cnblogs.com/wangkeqin/p/9338358.html