首页 > 解决方案 > 为什么不将具有默认参数的函数传递给模板化构造函数并使用 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

来自最后一个代码示例,我看不出为什么第一个不应该工作。有人可以解释为什么它不起作用吗?

编辑:在工作版本中遗漏了一个小细节,但仍然没有接近解释。

标签: c++functiontemplateslambdadefault-parameters

解决方案


您的第二个版本不采用test. 那的类型&testvoid (*)(int),不是void (*)()

这也是为什么你不能直接构造 a std::function<void()>from的原因test


推荐阅读