C++如何将字符串键映射到特定对象的类方法调用?
在C ++中,我试图将用户提供的字符串映射到特定对象的类方法调用。我成功地将用户提供的字符串映射到为另一个应用程序的功能调用,但是我不知道如何将这种方法扩展到用于为特定对象调用的类方法的工作。我将非常感谢任何帮助确定如何修复有缺陷的尝试实施的帮助:
void read_input(std::string& input_filename, Class_Name& my_object)
{
// Map string keys to object member invocation
std::map<const std::string, std::function<void (const std::string&)>> argument_map =
{
{"input_one", my_object.method_one},
{"input_two", my_object.method_two},
{"input_three", my_object.method_three}
};
std::ifstream input_file;
input_file.open(input_filename);
std::string line;
while (input_file)
{
std::getline (input_file, line);
std::stringstream argument_read(line);
std::string command;
std::string tmp;
argument_read >> command;
if (command[0] - '#' == 0) continue;
while (argument_read >> tmp)
{
if (tmp[0] - '#' == 0) break;
argument_map[command](tmp);
}
}
return;
}
In C++, I am trying to map a user-provided string to a class method invocation for a specific object. I was successful in mapping user-provided strings to function calls for another application, but I do not know how to extend this approach to work for class methods being invoked for a particular object. I would greatly appreciate any assistance in determining how to fix my attempted implementation that is flawed:
void read_input(std::string& input_filename, Class_Name& my_object)
{
// Map string keys to object member invocation
std::map<const std::string, std::function<void (const std::string&)>> argument_map =
{
{"input_one", my_object.method_one},
{"input_two", my_object.method_two},
{"input_three", my_object.method_three}
};
std::ifstream input_file;
input_file.open(input_filename);
std::string line;
while (input_file)
{
std::getline (input_file, line);
std::stringstream argument_read(line);
std::string command;
std::string tmp;
argument_read >> command;
if (command[0] - '#' == 0) continue;
while (argument_read >> tmp)
{
if (tmp[0] - '#' == 0) break;
argument_map[command](tmp);
}
}
return;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于所有方法都属于同一类并且具有相同的签名,因此您可以使用对成员函数的指针,使用成员访问
operator。 *
呼叫它们(nostd :: function
需要),例如:否则,您可以使用
std :: bind()
withstd :: function
,例如:或,您可以使用 lambdas 带有
std :: function :: function
,例如:Since all of the methods belong to the same class, and have the same signature, you can use Pointers to member functions, using the member access
operator.*
to call them (nostd::function
needed), eg:Otherwise, you can use
std::bind()
withstd::function
, eg:Or, you can use lambdas with
std::function
, eg: