std::成员函数指针的映射? [英] std::map of member function pointers?

查看:18
本文介绍了std::成员函数指针的映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用 对实现一个 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;
}

这篇关于std::成员函数指针的映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆