首页 > 解决方案 > 使用函数指针推迟函数执行

问题描述

我想从一个命令类创建一个变量,它将接收一个函数及其参数并在调用 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();
}

标签: c++templatesmember-function-pointers

解决方案


无需重新发明,只需使用std::functionand 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); };

推荐阅读