C++11 function

来源:互联网 发布:免费数据库 mysql p 编辑:程序博客网 时间:2024/04/29 10:11

function+bind可以实现按值传递函数对象,从而消灭多态(无需继承基类即可实现一般意义上的多态),消灭回调(回调本质上也是多态)。

参考:《C++ Primer 第五版中文版》《Linux 多线程服务端编程》

另见:面向接口编程

代码:

#include <map>#include <iostream>#include <string>#include <functional>using namespace std;int add(int i,int j) { return i+j;}class divide{public:int operator()(int i,int j){return i/j;}};class Big{public:bool bigger_than(int i,int j){return i>j;}};int main(int, char *[]){int i=10,j=5;auto mod = [](int i,int j){return i%j;};typedef function<int(int,int)> fun;map<string,function<int(int,int)>> binary_operators ;binary_operators.insert(make_pair<string,fun>("+",add));//函数指针binary_operators.insert(make_pair<string,fun>("-",std::minus<int>()));//函数对象binary_operators.insert(make_pair<string,fun>("/",divide()));//用户定义的函数对象binary_operators.insert(make_pair<string,fun>("*",[](int i,int j){return i*j;}));//未命名的lambdabinary_operators.insert(make_pair<string,fun>("%",mod));//命了名的lambdaBig big;fun f = std::bind(&Big::bigger_than,big,i,j);//调用big.bigger_than(i,j)binary_operators.insert(make_pair<string,fun>(">",f));//任意类的成员函数cout<<i<<"+"<<j<<"="<<binary_operators["+"](i,j)<<endl;cout<<i<<"-"<<j<<"="<<binary_operators["-"](i,j)<<endl;cout<<i<<"/"<<j<<"="<<binary_operators["/"](i,j)<<endl;cout<<i<<"*"<<j<<"="<<binary_operators["*"](i,j)<<endl;cout<<i<<"%"<<j<<"="<<binary_operators["%"](i,j)<<endl;cout<<i<<">"<<j<<"="<<binary_operators[">"](i,j)<<endl;return 0;};
输出:

10+5=15
10-5=5
10/5=2
10*5=50
10%5=0
10>5=1
请按任意键继续. . .




0 0
原创粉丝点击