std::成员函数指针的映射?

2022-01-07 00:00:00 c++ stl

我需要用 对实现一个 std::map.函数指针是指向拥有映射的同一类的方法的指针.这个想法是直接访问方法,而不是实现 switch 或等效的.

I need to implement an std::map with <std::string, fn_ptr> pairs. The function pointers are pointers to methods of the same class that owns the map. The idea is to have direct access to the methods instead of implementing a switch or an equivalent.

(我使用 std::string 作为地图的键)

( I am using std::string as keys for the map )

我对 C++ 很陌生,所以有人可以发布一些伪代码或链接来讨论使用函数指针实现映射吗?(指向拥有地图的同一类所拥有的方法的指针)

I'm quite new to C++, so could anyone post some pseudo-code or link that talks about implementing a map with function pointers? ( pointers to methods owned by the same class that owns the map )

如果您认为有更好的方法可以解决我的问题,也欢迎提出建议.

If you think there's a better approach to my problem, suggestions are also welcome.

推荐答案

这是我能想到的最简单的方法.请注意没有错误检查,地图可能会被设为静态.

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

#include <map>
#include <iostream>
#include <string>
using namespace std;

struct A {
    typedef int (A::*MFP)(int);
    std::map <string, MFP> 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;
}

相关文章