为给定的命令调用适当的方法
Calling the appropriate methods for a given command
我正在用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::function
和boost::bind
。
还要注意的是,您可能会发现编译器宏__FUNCTION__
(在编译时扩展到当前函数的未修饰名称,并且经常在错误消息中使用-您可能必须从成员函数名中去掉类名)在命令函数中很有用,以便在映射中按顺序注册函数,这样可以避免拼写错误和额外的键入。
(请注意,BOOST_CURRENT_FUNCTION
可能是一个更便携的宏。)
相关文章:
- 如何强制从重写方法调用重写的方法基方法?
- C++:使用方法调用析构函数的顺序是什么?
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 指向类方法调用的指针
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 是否有可以处理方法调用依赖关系的设计模式?
- 如何缩短C++中的方法调用?
- 从部分专用模板方法调用模板非静态方法
- 有没有办法禁止派生类中的基类方法调用?
- 为什么这C++只在编译器上编码一个不明确的方法调用Microsoft?
- 从父方法调用子方法
- 如何将子方法调用到父方法
- 虚拟函数在哪里使用 vpointer to vtable 来解析方法调用,非虚拟方法存储在哪里以及如何解析它们?
- 从静态方法调用静态函数指针
- 从同一类中的另一个方法调用方法时出错
- 方法调用意外地像 l 值一样起作用
- 无法从派生的一个方法调用基类方法
- 从类方法调用命名空间中名为 Same 的函数时,重载解析失败
- C 多线程JAVA JNI方法调用