【发布时间】:2020-06-25 21:59:57
【问题描述】:
我正在尝试创建一个类,该类存储指向其他类的成员函数的指针,并且可以从文本命令(如游戏控制台)执行。
根据此处找到的示例,我做了一些功能性的事情,它存储具有类似字符串的输入的成员。下面是我的实现。
文件: Command.hpp
#include <string>
#include <functional>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
class Command
{
public:
Command();
virtual ~Command();
void RegisterCommand(string command, function<void(const string&)> fun);
void Run(const string& command, const string& arg);
private:
unordered_map<string, function<void(const string&)>> functions;
};
文件: Command.cpp
Command::Command()
{
}
Command::~Command()
{
}
void Command::RegisterCommand(string command, function<void(const string&)> fun)
{
functions[command] = fun;
}
void Command::Run(const string& command, const string& arg)
{
functions[command](arg);
}
文件: main.cpp
#include "Command.hpp"
// function to register
void xyz_fun(const string& commandLine)
{
cout << "console output: " << commandLine << endl;
}
int main(int argc, char* argv[])
{
Command m_Cmd;
// Register function
m_Cmd.RegisterCommand("xyz_fun", xyz_fun);
// Run registered function
m_Cmd.Run("xyz_fun", "hello world.");
return EXIT_SUCCESS;
}
我的问题是如何实现一个通用类来存储具有未知输入参数(布尔值、整数、双精度值、字符串等)的成员。
例如,我可以这样做:
m_Cmd.RegisterCommand("xyz_fun2", xyz_function2);
然后打电话
m_Cmd.Run("xyz_fun2", false)
它有一个布尔参数而不是一个字符串。
提前感谢您的关注,欢迎提供任何帮助。
【问题讨论】:
-
如果
Run被错误的参数调用,你想发生什么? -
“存储指向成员函数的指针的类” -- 这与您的代码不匹配。您的代码使用函数对象,而不是函数指针。 (我建议保留代码并更改问题的文本和标题。函数对象看起来更适合您的目标。)
-
你如何决定传递哪个参数值?例如,为什么
m_Cmd.Run("xyz_fun2", false)而不是m_Cmd.Run("xyz_fun2", true)? -
你好,JaMiT。非常感谢您的 cmets。也许我表达得不好。我的目标是实现一个类来处理用户传递的命令。它们是简单的命令,其中大多数的唯一目的是更改一些现有的标志。例如:随着程序的运行,用户可以输入命令来改变窗口大小。或者通过文本文件以自动方式执行此操作(类似于脚本)。
-
抱歉我的困惑问题。我是 C++ 的新手。
标签: c++ class function-pointers