如何创建map< string,class :: method>在c + +并能够搜索函数并调用它? [英] How to create map<string, class::method> in c++ and be able to search for function and call it?
问题描述
我正在尝试在C ++中创建字符串和方法的映射,但我不知道该怎么做.我想做类似的事情(伪代码):
I'm trying to create a map of string and method in C++, but I don't know how to do it. I would like to do something like that (pseudocode):
map<string, method> mapping =
{
"sin", Math::sinFunc,
"cos", Math::cosFunc,
...
};
...
string &function;
handler = mapping.find(function);
int result;
if (handler != NULL)
result = (int) handler(20);
说实话,我不知道C ++是否有可能.我想要一个字符串,方法的映射,并能够在映射中搜索函数.如果存在给定的函数字符串名称,那么我想使用给定的参数来调用它.
To be honest I don't know is it possible in C++. I would like to have a map of string, method and be able to search for function in my mapping. If given string name of function exists then I would like to call it with given param.
推荐答案
好吧,我不是这里流行的Boost Lovers Club的成员,所以就这样-在原始C ++中.
Well, I'm not a member of the popular here Boost Lovers Club, so here it goes - in raw C++.
#include <map>
#include <string>
struct Math
{
double sinFunc(double x) { return 0.33; };
double cosFunc(double x) { return 0.66; };
};
typedef double (Math::*math_method_t)(double);
typedef std::map<std::string, math_method_t> math_func_map_t;
int main()
{
math_func_map_t mapping;
mapping["sin"] = &Math::sinFunc;
mapping["cos"] = &Math::cosFunc;
std::string function = std::string("sin");
math_func_map_t::iterator x = mapping.find(function);
int result = 0;
if (x != mapping.end()) {
Math m;
result = (m.*(x->second))(20);
}
}
很明显,如果我正确理解您想要的是方法指针,而不是函数/静态方法指针.
That's obviously if I have understood correctly that you want a method pointer, not a function/static method pointer.
这篇关于如何创建map< string,class :: method>在c + +并能够搜索函数并调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!