如何创建存储指向成员函数的指针的类 (C++)

How to create a class that stores pointers to member functions (C++)

本文关键字:函数 C++ 成员 指针 何创建 创建 存储      更新时间:2023-10-16

我正在尝试创建一个类,该类存储指向其他类的成员函数的指针,并且可以从文本命令(如游戏机(执行。

我根据此处找到的示例做了一些功能,该示例存储具有类似字符串输入的成员。下面是我的实现。

文件:命令.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;
};

文件:命令.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);
}

文件:主.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)

它有一个布尔参数而不是一个字符串。

提前感谢您的关注,欢迎任何帮助。

而不是

unordered_map<string, function<void(const string&)>> functions;

你可以做

union acceptable_types { int i; char c; bool b; std::string* s; ... };
unordered_map<string, function<void(acceptable_types)>> functions;

然后在调用函数时,只需将函数所需的值放入acceptable_types类型的变量中即可。
如果函数想要使用特定值,则它应该只使用acceptable_types联合的特定成员。

下面是一个示例:

#include "Command.hpp"
void
my_bool_func (acceptable_types union_param)
{
bool bool_var = union_param.b;
//      ...
//      Use bool_var
//      ...
}
void
my_string_func (acceptable_types union_param)
{
std::string string_var = *(union_param.s);
//      ...
//      Use string_var
//      ...
}
int
main(int argc, char* argv[])
{
Command my_command;
acceptable_types union_var;
my_command.RegisterCommand("my_bool_func", my_bool_func);
my_command.RegisterCommand("my_string_func", my_string_func);
union_var.b = true;
my_command.Run("my_bool_func", union_var);
*(union_var.s) = "hello world.";
my_command.Run("my_string_func", union_var);
return 0;
}