问题描述
以这个简化的例子为例:
Command.h:
class Command {
public:
template<typename Func>
Command(Func newToExecute) : toExecute([&newToExecute](){newToExecute();}) { }
void callFunction(); //defined in Command.cpp -> calls function with toExecute();
private:
std::function<void()> toExecute;
};
Main.cpp:
void test(int var = 0) {
//does irrelevant things
}
int main() {
Command testCommand(test);
testCommand.callFunction();
return 0;
}
尝试运行此程序时,我从使用 MinGW 的编译器收到错误消息:
error: too few arguments to function Command(Func newToExecute) : toExecute([&newToExecute](){newToExecute();}) { }
现在我不会为了保存一个简单的 void 函数而做这一切,如果这不起作用:
//in the Command class:
Command(std::function<void()> newToExecute) : toExecute(std::move(newToExecute)) { } //rest unchanged
//in the main function:
Command testCommand([](){test();}); //rest unchanged
从最后一个代码示例来看,我看不出为什么第一个不工作。谁能解释一下为什么它不起作用?
编辑:在工作版本中遗漏了一个小细节,但仍不接近解释。
解决方法
您的第二个版本不采用 test
的地址。该 &test
的类型是 void (*)(int)
,而不是 void (*)()
。
这也是您不能直接从 std::function<void()>
构造 test
的原因。