std::map of member function pointers?

前端 未结 4 2019
悲&欢浪女
悲&欢浪女 2020-12-03 01:14

I need to implement an std::map with pairs. The function pointers are pointers to methods of the same class that owns t

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 02:02

    Another option is to use delegates as oppose to function pointers. This delegate implementation is pretty fast, supports polymorphisms, and plays well with stl containers. You could have something like:

    class MyClass {
    public:
        // defines
        typedef fastdelegate::FastDelegate2 MyDelegate;
        typedef std::map MyMap;
    
        // populate your map of delegates
        MyClass() {
            _myMap["plus"] = fastdelegate::MakeDelegate(this, &Plus);
            _myMap["minus"] = fastdelegate::MakeDelegate(this, &Minus);
        }
    
        bool Do(const std::string& operation, int a, int b, int& res){
            MyMap::const_iterator it = _myMap.find(operation);
            if (it != _myMap.end()){
                res = it.second(a,b);
                return true;
            }
    
            return false; 
        }
    private:
        int Plus (int a, int b) { return a+b; }
        int Minus(int a, int b) { return a-b; }
        MyMap _myMap;    
    };      
    

提交回复
热议问题