天天看點

C++11: function type

#include <functional>
#include <map>
#include <string>
#include <iostream>

int add(int i, int j) { return i +j; }


struct divide {
        int operator()(int denominator, int divider) {
                return denominator / divider;
        }
};

int main()
{
        auto mod = [](int i, int j) { return i %j; };
        std::map<std::string, std::function<int (int, int)> > binops = { 
                {"+", add},
                {"-", std::minus<int>()},
                {"*", [](int i, int j){ return i * j; }}, 
                {"/", divide()},
                {"%", mod},

        };

        std::cout << "16 + 4 = " << binops["+"](, ) << std::endl;
        std::cout << "16 - 4 = " << binops["-"](, ) << std::endl;
        std::cout << "16 * 4 = " << binops["*"](, ) << std::endl;
        std::cout << "16 / 4 = " << binops["/"](, ) << std::endl;
        std::cout << "16 % 4 = " << binops["%"](, ) << std::endl;

        return ;
}

           
// from C++ primer 5th(p.578)
// g++ xx.cpp -std=c++11
// gcc 4.9.2
           

繼續閱讀