从 std::map 调用函数
Calling functions from a std::map
我正在尝试构建 Object
来充当我的函数的处理程序。为了解释原因,我将使用它来扫描用户输入,检查地图是否匹配。如果找到匹配项,我将调用该函数并将 user-inputted 行的其余部分复制到该函数;
class Object
{
public:
Object(std::map<std::string, void(*)(const std::string&)> MAP)
{/*...code...*/};
};
快速示例代码:
class Main
{
public:
void testFunc(const std::string& A)
{
}
void construct()
{
Object{
std::map<std::string, void(*)(const std::string&)> {
{"exit", [](const std::string &A){ exit(1); }},
//{"test1", (void(Main::*)(const std::string&))&testFunc},
//{"test2", [](const std::string &A){ testFunc(A); }},
//{"test3", [this](const std::string &A){ testFunc(A); }},
{"NULL", NULL}
}
};
}
};
注释行都没有工作,产生了不同的错误,但其他行成功了并且没有运行时错误(好吧,NULL 应该是,但我正在处理它)。
我的问题是,我是否正确地想象了这个机制,如果没有,我是否应该只保存指针并稍后转换为函数?是否可以在仅在 class 范围内定义的对象中保存引用和调用函数(调用也会从 class 内部进行)?
很多问题..我知道。但我以前从未见过这样做的..所以我想这可能是一个很好的理由。
因为我没有指出错误,here is a link;
Non-static
成员函数与非成员函数的不同之处在于它们采用额外的隐式参数 - class 实例。 Main::testFunc
需要两个参数:Main
和 std::string const&
。但是您的界面只允许一个参数。使这项工作起作用的唯一方法是创建一个函数将引用的全局 Main*
- 这是一个非常脆弱的设计。
相反,您可以使用 std::function<void(std::string const&)>
让您的界面更通用。这是 any 可调用函数,它接受 std::string const&
,而不仅仅是指向函数的指针。这将允许您编写最后一个版本:
{"test3", [this](const std::string &A){ testFunc(A); }},
并且可能是您最好的选择。
我正在尝试构建 Object
来充当我的函数的处理程序。为了解释原因,我将使用它来扫描用户输入,检查地图是否匹配。如果找到匹配项,我将调用该函数并将 user-inputted 行的其余部分复制到该函数;
class Object
{
public:
Object(std::map<std::string, void(*)(const std::string&)> MAP)
{/*...code...*/};
};
快速示例代码:
class Main
{
public:
void testFunc(const std::string& A)
{
}
void construct()
{
Object{
std::map<std::string, void(*)(const std::string&)> {
{"exit", [](const std::string &A){ exit(1); }},
//{"test1", (void(Main::*)(const std::string&))&testFunc},
//{"test2", [](const std::string &A){ testFunc(A); }},
//{"test3", [this](const std::string &A){ testFunc(A); }},
{"NULL", NULL}
}
};
}
};
注释行都没有工作,产生了不同的错误,但其他行成功了并且没有运行时错误(好吧,NULL 应该是,但我正在处理它)。
我的问题是,我是否正确地想象了这个机制,如果没有,我是否应该只保存指针并稍后转换为函数?是否可以在仅在 class 范围内定义的对象中保存引用和调用函数(调用也会从 class 内部进行)?
很多问题..我知道。但我以前从未见过这样做的..所以我想这可能是一个很好的理由。
因为我没有指出错误,here is a link;
Non-static
成员函数与非成员函数的不同之处在于它们采用额外的隐式参数 - class 实例。 Main::testFunc
需要两个参数:Main
和 std::string const&
。但是您的界面只允许一个参数。使这项工作起作用的唯一方法是创建一个函数将引用的全局 Main*
- 这是一个非常脆弱的设计。
相反,您可以使用 std::function<void(std::string const&)>
让您的界面更通用。这是 any 可调用函数,它接受 std::string const&
,而不仅仅是指向函数的指针。这将允许您编写最后一个版本:
{"test3", [this](const std::string &A){ testFunc(A); }},
并且可能是您最好的选择。