我需要实施一个std::map
with <std::string, fn_ptr>
对。函数指针是指向拥有该映射的同一类的方法的指针。这个想法是直接访问这些方法,而不是实现开关或等效的东西。
( 我在用std::string
作为地图的键)
我对 C++ 很陌生,所以有人可以发布一些伪代码或链接来讨论使用函数指针实现映射吗? (指向拥有映射的同一类所拥有的方法的指针)
如果您认为有更好的方法来解决我的问题,也欢迎提出建议。
这是我能想到的最简单的。请注意,没有错误检查,并且地图可能可以有效地静态化。
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)