- if…else语句
- switch…case语句
- 使用map表,key = function_name,value_name = function_pointer.
分以下几种情况:
- 对于需要分支结构的情况,如果分支较少,简简单单使用if或者switch是没有什么区别的,也没有必要使用map;
- 对于分支较多的情况,理论上switch…case结构效率比if高,因为switch…case底层使用的是跳跃表的东西,查表是要比一一比较来的快很多;
- 也有一种极端情况,可能需要几百个分支,甚至更多,这个时候如果写分支之类的,会很头疼,map是不错的选择,但是有一个局限性,函数参数是要一样的。
int func001(int a)
{
return -1;
}
int func002(int b)
{
return 0;
}
//...
std::map<std::string, int(*)(int)> func_map;
void init_map() {
func_map.insert(std::pair< std::string, int(*)(int)>("func001", func001);
func_map.insert(std::pair< std::string, int(*)(int)>("func002", func002);
}
void switch_func(std::string msgName)
{
iter = func_map.find(msgName);
if (iter != func_map.end()) {
iter->second(0);
}
else {
//没找到,报错
}
}
if…else和switch…case都有长度限制,默认最多255个吧,数量是有限的。
总的来说,看应用场景,函数调用太多也是有开销的,看我们怎么抉择吧。