这很容易。将名称映射到年龄函数。
typedefs 使函数指针更容易,静态本地映射使它只被初始化一次,然后“缓存”结果。无序地图非常适合这种事情。
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;
}
所有这些代码都在我的脑海中,并且可能无法按原样编译。
实际上,我强烈建议不要每个人都拥有一个功能,而是使用数据。如果绝对需要,请使用枚举而不是字符串来识别它们。