为什么不将带有默认参数的函数传递给模板化构造函数并使用 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 的原因。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...