function+bind可以实现按值传递函数对象
从而而消灭多态(无需继承基类即可实现一般意义上的多态)
本质上是对象消息机制,可以向任何对象传递消息并执行,只需要规定消息的格式,这个格式就是函数对象的声明。
本文示例代码:参考《C++ Primer 第五版中文版》
思想参考:《Linux 多线程服务端编程》以及 孟岩的 function/bind的救赎(上)
另见:面向接口编程
代码:
#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; }));//未命名的lambda
binary_operators.insert(make_pair<string, fun>("%", mod));//命了名的lambda
Big big;
auto f = std::bind(&Big::bigger_than, big, std::placeholders::_1, std::placeholders::_2);//调用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
请按任意键继续. . .