我需要实现std::map
与<std::string, fn_ptr>
对.函数指针是指向拥有映射的同一类的方法的指针.我们的想法是直接访问方法,而不是实现交换机或等效方法.
(我std::string
用作地图的键)
我对C++很陌生,所以有人会发布一些伪代码或链接来讨论用函数指针实现一个映射吗?(指向拥有地图的同一个类所拥有的方法的指针)
如果您认为我的问题有更好的方法,也欢迎提出建议.
小智 32
这是我能想到的最简单的事情.注意没有错误检查,并且地图可能有用地变为静态.
#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;
}
Run Code Online (Sandbox Code Playgroud)