为给定的命令调用适当的方法

Calling the appropriate methods for a given command

本文关键字:方法 调用 命令      更新时间:2023-10-16

我正在用C++制作一个命令提示符。我希望用户输入一行,例如"说点什么"。然后将其拆分为"say"作为命令名,"something"作为参数。到目前为止,一切都很好——这已经奏效了。

然后,我想使用命令的名称来调用适当的方法。我可以使用某种查找表,但有更好的方法吗?

您可能需要类似命令关键字和函数或方法指针的映射之类的东西

#include <string>
#include <map>
class CmdHandler // our handler class
{
public:
    void Handler(const std::string &arg){}//our handler method
};

typedef void (CmdHandler::*MethodPtr)(const std::string &); // make typedef to easily deal with the type of the member-function pointer
std::map<std::string, MethodPtr> my_handlers; // make our method lookup table
int _tmain(int argc, _TCHAR* argv[])
{
    CmdHandler handler;
    //add a real member-function pointer for the "say" command
    my_handlers.insert(std::make_pair("say", &CmdHandler::Handler));
    //look for the handler of command "say" and call it instantly 
    (handler.*my_handlers["say"])("something");
    return 0;
}

C++不支持任何类型的反射:某种将名称映射到函数对象的表是我所知道的最好的方法。

查找表是常用的方法。通常,std::map。。。如果你正在使用boost,你可能想看看boost::functionboost::bind

还要注意的是,您可能会发现编译器宏__FUNCTION__(在编译时扩展到当前函数的未修饰名称,并且经常在错误消息中使用-您可能必须从成员函数名中去掉类名)在命令函数中很有用,以便在映射中按顺序注册函数,这样可以避免拼写错误和额外的键入。

(请注意,BOOST_CURRENT_FUNCTION可能是一个更便携的宏。)