作者:浪漫满屋19860902692 | 来源:互联网 | 2022-12-01 19:46
1> Paul Belange..:
您可以实现从命令字符串到使用a处理该命令的函数的实现的映射unordered_map
.
示例实现可以如下工作:
// A function handler takes its arguments as strings and returns some sort of result
// that can be returned to the user.
using CommandHandler = std::function const&)>
// various handers for command requests
Result handle_print(std::vector const& args);
Result handle_delete(std::vector const& args);
Result handle_add(std::vector const& args);
Result handle_version(std::vector const& args);
// the table that holds our commands
std::unordered_map command_table = {
{"print", handle_print},
{"delete", handle_delete},
{"add", handle_add},
{"version", handle_version},
};
// take your json doucment, extract the first value as the command, and put the rest into an arg array:
void handle_request(Connection& connection, json const& request)
{
std::string cmd = root["A"];
std::vector args;
// parse the rest of your arguments into an array here.
if(command_table.count(cmd))
{
// command is valid
auto& handler = command_table[cmd];
auto result = handler(args);
send_result(connection, result);
}
else
{
// send bad command error or something
send_bad_command(connection);
}
}