我最近写了很多重复的代码。我需要想出一个更好的解决方案。
至于现在我正在做这件事(伪代码)
std::map<std::string/*commandname*/, commandfunction*> Commands;
void OnPlayerExecuteCommand(cplayer* player, std::string command, std::string parameters)
{
//find check blablabla yaddayadda then..
Commands[command]->execute(player, parameters);
}
//heal PlayerId/Name (float)amount
void Command_HealMe(cplayer* player, std::string parameters)
{
SomeParsingCodeA(params);//get the cplayer* from playername or id and float heal amount
}
//vehicle name color1 color2, eg /vehicle Ferrari 0xFF0000 123456
void Command_SpawnVehicle(cplayer* player, std::string parameters)
{
SomeParsingCodeB(params);//get the vehiclename, and colors
}
//kick playername/id reason, eg /kick player_a you are spamming the chat
void Command_KickSomeone(cplayer* player, std::string parameters)
{
SomeParsingCodeC(params);//get cplayer* of playername or id, and get the rest string
}但每个SomeParsingCode*代码片段都包含许多重复的代码,如IsValidPlayer(string)//returns Cplayer from id or name,将字符串解析为数字或浮点数或其他任何内容。
我正在考虑通过创建一个通用的解析函数来简化代码的编写,比如:
auto result = ParseMyParameters("Player_string_or_int;int_or_hex;int_or_hex",input) if(result.good()){ //continue
我在考虑将每个请求映射到一个字符,如下所示:
character - expected input
u - PlayerName as String or PlayerID as integer(u as in user)
i - integer number
x - hex formatted number
f - real number
g - integer or hex
w - one worded string
r - return remaining string,
like /kick player_a you are spamming the chat
would be parsed with "ur", and the result would be a cplayer pointer and the string "you are spamming the chat"然后创建一个函数,循环一个字符串,逐个解析所有请求的内容。
但是我在想,C++有这么多好东西,我真的不知道在这种情况下应该使用什么,我可以使用哪些容器或boost/C++来完成这项任务?在C++中有没有什么东西可以让我来做呢?推荐使用哪种方法?
此外,这可能需要一些可变参数,使用varargs或我可以使用一些可变模板?喜欢
ParseString<cplayer*,int,float,std::string>("Joe 5 5.0 hello my friend!");
使用
std::string = "hello my friend!";
或
ParseString<cplayer*,int,float,std::vector<std::string>>("Joe 5 5.0 hello my friend!");
使用std::vector<std::string> = {"hello", "my", "friend!"};
发布于 2014-11-16 05:36:42
使用LEX (FLEX)或YACC (BISON)做这类事情要容易得多。
您可以使用它们来定义命令,并在遇到命令时提供操作。
https://stackoverflow.com/questions/26950918
复制相似问题