根据需求的不同 选择不同的策略算法
之前是保存的各种策略类的指针
这里直接使用 function bind 选择对应的算法
代码
// 005.cpp: 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <functional> #include <iostream>using namespace std;int MyAdd(int a, int b) { return a + b; }class MyMinus { public:int operator()(int a, int b) {return a - b;} };class binary_operators { public:typedef std::function<int(int, int)> FUNC;binary_operators(FUNC f,int a, int b) :func_(f),left(a), right(b),result(0) {}int GetResult() { return func_(left, right); } private:std::function<int(int, int)> func_;int left;int right;int result; };int main() {binary_operators addOperation(std::function<int(int, int)>(MyAdd),1,2);binary_operators minusOperation(std::function<int(int, int)>(MyMinus()), 5, 7);std::cout << "addOperation(1,2) result: " << addOperation.GetResult() << std::endl;std::cout << "minusOperation(5,7) result: " << minusOperation.GetResult() << std::endl;return 0; }