问题描述
void setParamater(std::string key,std::string value){
if(key == KEYParaM_1)
{
//Do something
}
else if(key == KEYParaM_2)
{
//Do something
}
else if (key == KEYParaM_3)
{
//Do something
}
else if (key == KEYParaM_4)
{
//Do something
}
else if (key == KEYParaM_5)
{
//Do something
}
else if (key == KEYParaM_6) {
//Do something
}
else
{
//Do something
}
}
-
我觉得这很丑陋,并且它的代码可以进行许多不必要的比较(参数越多,比较对象就越多。)
-
我的想法是制作一个
map
的字符串和函数:std::map<std::string; std::funtion<std::string>>
来替换此代码。 -
第一个
std::string
将是键,std::function
将替换//Do something
行中的代码,而其他std::string
将是值。 / p> -
此解决方案的缺点是,我将为每个
key
创建一个对象,并且必须找到一个声明所有函数的好地方。好消息是,它易于调用,不会进行所有比较复杂的比较。像这样的东西会很漂亮:
void setParamater(std::string key,std::string value){
my_map(key,f(value)); //I'm not sure about the Syntax in there
}
- 有人会更好地替换if-else链吗?
map
是个好主意吗?
-FYI:每个案例所做的事情都不尽相同,不仅仅是二传手。
谢谢!
解决方法
您不需要为std::function
声明一个函数。替代方法是使用lambda。该lambda可以直接用于您的地图初始化。
看起来像
std::map<std::string,std::function<void(std::string)> funcs {
std::make_pair(KEYPARAM_1,[](std::string s) { std::cout << s; },std::make_pair(KEYPARAM_2,[](std::string s) { /* something else */ }
}