c++ - 为什么不将具有默认参数的函数传递给模板化构造函数并使用 lambda 将其存储为 std::function工作?
问题描述
以这个简化的例子为例:
命令.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;
};
主要.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 (*)()
。
这也是为什么你不能直接构造 a std::function<void()>
from的原因test
。
推荐阅读
- javascript - 如何循环和创建动态引导网格
- javascript - 在 React 中无延迟地交换视频组件
- python - 决策树算法的图形表示问题
- python - _tkinter.TclError:错误选项“-initialdir”:必须是 -defaultextension、-filetypes、-initialdir、-initialfile 或 -typevariable
- c++ - 在 bzhi(y, tzcnt(x)) 中避免不必要的 mov ecx, ecx 指令
- multithreading - 在这种情况下我应该使用哪种 ZMQ 模式?
- r - 如何找到最频繁的类别?
- graphql-js - 如果获得超过 1 个模式,Graphql 工具 mergeSchemas 会抛出错误
- flutter - 输入'未来
' 不是类型 'Future 的子类型 ' - linux - rsync 如何同步到 192.168... 和 /sdb