std::map of member function pointers?

前端 未结 4 2023
悲&欢浪女
悲&欢浪女 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 01:48

    This is about the simplest I can come up with. Note no error checking, and the map could probably usefully be made static.

    #include 
    #include 
    #include 
    using namespace std;
    
    struct A {
        typedef int (A::*MFP)(int);
        std::map  fmap;
    
        int f( int x ) { return x + 1; }
        int g( int x ) { return x + 2; }
    
    
        A() {
            fmap.insert( std::make_pair( "f", &A::f ));
            fmap.insert( std::make_pair( "g", &A::g ));
        }
    
        int Call( const string & s, int x ) {
            MFP fp = fmap[s];
            return (this->*fp)(x);
        }
    };
    
    int main() {
        A a;
        cout << a.Call( "f", 0 ) << endl;
        cout << a.Call( "g", 0 ) << endl;
    }
    

提交回复
热议问题