微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么不将带有默认参数的函数传递给模板化构造函数并使用 lambda 将其存储为 std::function<void()> 工作?

如何解决为什么不将带有默认参数的函数传递给模板化构造函数并使用 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?