假设有人按照以下方式分别为每个人做了单独的功能:
void John_age(void);
void Tom_age(void);
void Kate_age(void);
void Cathy_age(void);
......................
确定他们的年龄。
现在我想创建这样一个函数来仅使用人名来调用这些函数,例如:
void age(char* NAME){...}
为那个人“名字”调用特定函数。
void NAME_age(void);
在 C++ 或 C 中有什么简单的方法可以做到这一点吗?我将衷心感谢您的帮助。谢谢。
我用于微 Controller 的 IDE 为每个单独的引脚 X
生成格式为 void X_functionName(void);
的可执行函数。所以我一直在寻找一种更通用的方法来使用 void customName(const char* X)
等函数轻松调用它们。
最佳答案
这很容易。制作姓名与年龄功能的映射。
typedef 使函数指针更容易,而静态局部映射使其只被初始化一次,然后“缓存”结果。无序映射非常适合这类事情。
C++11:
void age(const std::string& NAME){
static const std::unordered_map<std::string, void(*)()> age_lut = {
{"John",John_age},
{"Tom",Tom_age},
{"Kate",Kate_age},
{"Cathy",Cathy_age},
};
return age_lut.at(Name); //throws std::out_of_range if it doesn't exist
}
C:(这里我用的是线性映射而不是像C++那样的散列,因为我懒)
typedef void(*)() get_age_func_type;
typedef struct {
const char* name;
get_age_func_type func;
} age_lut_type;
age_lut_type age_lookup_table[] = {
{"John",John_age},
{"Tom",Tom_age},
{"Kate",Kate_age},
{"Cathy",Cathy_age},
};
const unsigned age_lookup_table_size =
sizeof(age_lookup_table)/sizeof(age_lut_type);
bool age(char* NAME){
bool found = false;
//if you have a large number of functions,
//sort them in the initialization function, and
//use a binary search here instead of linear.
for(int i=0; i<age_lookup_table_size ; ++i) {
if (stricmp(age_lookup_table[i], NAME)==0) {
age_lookup_table[i].func();
found = true;
break;
}
}
return found;
}
所有这些代码都不在我的脑海中,可能无法按原样编译。
实际上,我强烈建议不要为每个人设置函数,而是使用数据。如果绝对需要,请使用枚举而不是字符串来标识它们。
关于c++ - 调用函数的动态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17532293/