我假设cmdParseOption()
的第三个参数是const char *
。
在C++中的任何版本,
#include<string>
#include <map>
typedef void (*function)();
void func1() {}; // we want to call this function for "-doit1"
void func2() {}; // we want to call this function for "-doit2"
int main()
{
std::map<std::string, function> option_map;
option_map["-doit1"] = func1;
option_map["-doit2"] = func2;
// etc
for (std::map<std::string>::const_iterator i = option_map.begin(), end = option_map.end(); i != end; ++i)
{
if (cmdParseOption(&argc, &argv, i->first.c_str())
{
// we've found a match in the map. Call the corresponding function
(i->second)();
}
}
return 0;
}
如果你想30点或300的选择,所有需要改变的是建立地图 - 循环保持不变。
在C++ 11及更高版本,这可以简化一点
#include<string>
#include <map>
typedef void (*function)();
void func1() {}; // we want to call this function for "-doit1"
void func2() {}; // we want to call this function for "-doit2"
int main()
{
std::map<std::string, function> option_map{
{"-doit1", func1},
{"-doit2", func2}
};
for (auto &i : option_map)
{
if (cmdParseOption(&argc, &argv, i.first.c_str())
{
(i.second)();
}
}
return 0;
}
如果你想其他类型的回调,也有丰富的选择 - 无论是在功能类型方面,并在设施标准库。
如果你想引入另一个检查(如呼叫ecmdParseOption()
而不是cmdParseOption()
在你的第二个else if
)只需设置第二图,填充它,并根据需要遍历它。
这正是我所期待的。有一种感觉,矢量/地图可能解决我的问题,但没有很多与他们的经验。谢谢! – BoredMatt