[英]passing lambda as a constructor argument
I am trying to store a callback function in a class, so I can create different instances with different callback. 我试图将回调函数存储在一个类中,以便可以使用不同的回调创建不同的实例。 Unfortunately stackoverflow forces me to write more useless stuff, saying my post is mostly code. 不幸的是,stackoverflow迫使我写更多无用的东西,说我的帖子主要是代码。 However I don't see any troubles instantly understand my question by looking at the code below. 但是,通过查看下面的代码,我看不到任何麻烦可以立即理解我的问题。
Can't understand why this doesn't work: 无法理解为什么这行不通:
#include <iostream>
#include <functional>
class A {
public:
A(std::function<void()> lambda) : lambda_{lambda} {};
void Run() { lambda_(); };
private:
std::function<void()> lambda_;
};
auto main() -> int {
auto q = []{};
A(q) a;
a.Run();
}
Error: 错误:
1.cpp:15:10: error: expected ‘;’ before ‘a’
A(q) a;
^
While this does: 虽然这样做:
#include <iostream>
#include <functional>
void A(std::function<void()> lambda) {
lambda();
};
auto main() -> int {
auto q = []{};
A(q);
}
The syntax for passing constructor arguments in a variable declaration is: 在变量声明中传递构造函数参数的语法为:
A a(q);
More generally, the different ways of declaring variables are: 更一般地,声明变量的不同方法是:
TypeName variableName; // no arguments
TypeName variableName(); // WRONG: this is a function declaration
TypeName variableName(arg1, arg2, ...);
And with C++11 uniform initialization : 并使用C ++ 11 统一初始化 :
TypeName variableName{}; // no arguments
TypeName variableName{arg1, arg2, ...};
The correct syntax for initializing an object a
with parameter q
is 使用参数q
初始化对象a
的正确语法是
A a(q);
not 不
A(q) a;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.