【发布时间】:2020-03-26 08:12:44
【问题描述】:
我有一个想法来制作超快速的命令解析器。
我有100多对命令-函数,有些命令有相同的前缀。
下面是我的想法的例子。我可以制作一个程序来生成像这个例子中那样的 C++ 代码,但我认为这可以通过模板来实现。
我不擅长模板。有人可以帮忙吗?
static const string_view s1{"hello"};
void f1() { cout << "f1" << endl; }
static const string_view s2{"helly"};
void f2() { cout << "f2" << endl; }
static const string_view s3{"hi jo"};
void f3() { cout << "f3" << endl; }
static const string_view s4{"hoyMo"};
void f4() { cout << "f4" << endl; }
void sw(string_view& hw){
switch(hw.size()){
case 5: {
switch(hw[0]){
case 'h': {
switch(hw[1]){
case 'e': {
switch(hw[2]){
case 'l': {
switch(hw[3]){
case 'l': {
switch(hw[4]){
case 'o': {
f1();
break;
}
case 'y': {
f2();
break;
}
default: cout << "command not found" << endl; break;
}
break;
}
default: cout << "command not found" << endl; break;
}
break;
}
default: cout << "command not found" << endl; break;
}
break;
}
case 'i': {
if(hw.substr(2) == s3.substr(2)){
f3();
}
break;
}
case 'o': {
if(hw.substr(2) == s4.substr(2)){
f4();
}
break;
}
default: cout << "command not found" << endl; break;
}
break;
}
default: cout << "command not found" << endl; break;
}
break;
}
case 6: {
//...
break;
}
default: cout << "command not found" << endl; break;
}
}
int main(){
string_view myCommand("hi jo");
sw(myCommand);
string_view myCommand2("hoyMo");
sw(myCommand2);
string_view myCommand3("ha ha");
sw(myCommand3);
}
【问题讨论】:
-
"...可能有人可以帮忙吗?...":这非常接近 "请为我编写代码"。请阅读How to Ask 并附上您的实施尝试。
-
你应该看看 Boost Spirit。
-
使用 map 会比嵌套 switch case 语句更好。
-
我不确定您要如何或为什么要使用模板转换此代码。