How to create map in c++ and be able to search for function and call it?

前端 未结 7 937
予麋鹿
予麋鹿 2021-01-01 15:25

I\'m trying to create a map of string and method in C++, but I don\'t know how to do it. I would like to do something like that (pseudocode):

map

        
7条回答
  •  粉色の甜心
    2021-01-01 16:04

    Well, I'm not a member of the popular here Boost Lovers Club, so here it goes - in raw C++.

    #include 
    #include 
    
    struct Math
    {
        double sinFunc(double x) { return 0.33; };
        double cosFunc(double x) { return 0.66; };
    };
    
    typedef double (Math::*math_method_t)(double);
    typedef std::map math_func_map_t;
    
    int main()
    {
    
        math_func_map_t mapping;
        mapping["sin"] = &Math::sinFunc;
        mapping["cos"] = &Math::cosFunc;
    
        std::string function = std::string("sin");
        math_func_map_t::iterator x = mapping.find(function);
        int result = 0;
    
        if (x != mapping.end()) {
            Math m;
            result = (m.*(x->second))(20);
        }
    }
    

    That's obviously if I have understood correctly that you want a method pointer, not a function/static method pointer.

提交回复
热议问题