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

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

问题描述

我需要实现 std :: map < std :: string,fn_ptr> 函数指针是指向拥有地图的同一类的方法的指针。

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 :: map的成员函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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