函数表(function table) 和 函数(function)容器的用法
本文地址: http://blog.csdn.net/caroline_wendy/article/details/15416015
函数表(function table),是函数映射的表, 最简单的方法是使用"map<>"容器, 映射"std::string"和"function<>"容器;
函数容器的类型是 调用签名(call signature), 如 "std::function<int (int, int)>";
可以存储, 函数, Lambda表达式, 函数对象类(function-object class), 标准库的函数对象等.
代码如下:
- /*
- * CppPrimer.cpp
- *
- * Created on: 2013.11.11
- * Author: Caroline
- */
- /*eclipse cdt*/
- #include <iostream>
- #include <functional>
- #include <map>
- #include <string>
- using namespace std;
- int add (int i, int j) { return i+j; }
- auto mod = [](int i, int j) { return i%j; };
- struct divide {
- int operator() (int denominator, int divisor) {
- return denominator / divisor;
- }
- };
- int main (void) {
- std::map<std::string, std::function<int (int, int)> > binops = {
- {"+", add},
- {"-", std::minus<int>()},
- {"/", divide()},
- {"*", [](int i, int j) { return i*j; }},
- {"%", mod}
- };
- std::cout << "10 + 5 = " << binops["+"] (10, 5) << std::endl;
- std::cout << "10 - 5 = " << binops["-"] (10, 5) << std::endl;
- std::cout << "10 / 5 = " << binops["/"] (10, 5) << std::endl;
- std::cout << "10 * 5 = " << binops["*"] (10, 5) << std::endl;
- std::cout << "10 % 5 = " << binops["%"] (10, 5) << std::endl;
- return 0;
- }