如何解决为什么不将带有默认参数的函数传递给模板化构造函数并使用 lambda 将其存储为 std::function<void()> 工作?
以这个简化的例子为例:
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
的原因。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。