c++ - 使用函数指针推迟函数执行
问题描述
我想从一个命令类创建一个变量,它将接收一个函数及其参数并在调用 Execute 时执行它,但我不知道如何将构造函数参数传递给类成员变量,因为我不知道如何函数指针将是。
这是我想到的一些伪代码。
class Command {
public:
template<_Fn, _Args...>
Command(_Fn&& _function, _Args&&... _args)
{
}
void Execute(){
}
};
void Print(int _int, float _float){
...
}
void Print(const char* _text, unsigned int _uint){
...
}
int main(){
Command cmd0 = Command(&Print, 5, 6.2f);
Command cmd1 = Command(&Print, "Hello", 2u);
cmd1.Execute();
cmd0.Execute();
}
解决方案
无需重新发明,只需使用std::function
and std::bind
:
int main(){
std::function<void()> cmd0 = std::bind(&PrintIntFloat, 5, 6.2f);
std::function<void()> cmd1 = std::bind(&PrintStringInt, "Hello", 2u);
cmd1();
cmd0();
}
请注意,我重命名了这些函数,因为在 C++ 中解除重载集是有问题的。
或者您可以使用 lambdas 在这种情况下不需要提升(感谢 deW1 的建议):
std::function<void()> cmd0 = [] { Print(5, 6.2f); };
std::function<void()> cmd1 = [] { Print("Hello", 2u); };
推荐阅读
- javascript - 如何将样式设置为 tileLayer?
- python - list.remove(x): x 不在随机数列表中
- excel - microsoft excel 2016 是否具有谷歌表格中可用的函数“=googleFinance()”?
- sql - 比较 2 个不同的表并根据条件选择值
- heroku - 当 env 变量中不可用时,如何获取 heroku SendGrid 插件用户名和密码?
- python - Python 通过 id 获取对象
- flutter - 在 Flutter 中对齐小部件而不使用 Stack
- javascript - 如何从Javascript中的经过时间中删除小数(毫秒)?
- clojure - 我可以从 Clojure 的宏中引用宏吗?
- r - 对所有 x 值求和并减去它们的平均值