为什么不将具有默认参数的函数传递给模板化构造函数并使用 lambda 将其存储为 std::function<void()> 工作?
Why doesn't passing a function with default parameters to a templatized constructor and storing it using a lambda as std::function<void()> work?
举个简单的例子:
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 (*)()
。
这也是为什么你不能直接从 test
构造 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 (*)()
。
这也是为什么你不能直接从 test
构造 std::function<void()>
的原因。