[英]Passing a function as a parameter to another function C++
I am trying to pass my function called read into another function called start. 我正在尝试将名为read的函数传递给另一个名为start的函数。
void MainPage::read() {
...
}
void MainPage::start(std::function< void() > func) {
...
}
The line which is giving me issues and calls the start function is this one. 给我提出问题并调用启动功能的这一行就是这一行。 It is in my main function.
这是我的主要功能。
start( read );
When I try to compile this, I get an error which isn't of much help to me. 当我尝试编译它时,我得到一个对我没有多大帮助的错误。
C3867 'App1::MainPage::read': non-standard syntax; use '&' to create a pointer to member
I can't reproduce it now, but while trying to pass the parameter in different ways I came across another error which was something like this: 我现在无法重现它,但在尝试以不同的方式传递参数时,我遇到了另一个错误,如下所示:
C2664 void App1::MainPage::start(std::function<void (void)>cannot convert argument 1 from 'void(void)' to 'std::function<void (void)>
I'm using VS2015 Community and working in C++. 我正在使用VS2015社区并使用C ++。
The problem is that you are trying to pass a method pointer here, not a function pointer. 问题是你试图在这里传递方法指针,而不是函数指针。 Methods have a hidden
this
parameter that would be left unbound just by passing read
. 方法有一个隐藏的
this
参数也只是通过传递来未被结合read
。 That kind of expression is known as a pointer to member. 这种表达式被称为指向成员的指针。
The first major difference in syntax is that a method pointer must be qualified with its enclosing type, and you need the &
operator in front of the name. 语法的第一个主要区别是方法指针必须使用其封闭类型进行限定,并且在名称前需要
&
运算符。 This would give you &MainPage::read
, which is a valid pointer-to-member expression. 这将为您提供
&MainPage::read
,这是一个有效的指向成员的表达式。
The second step is to bind the hidden this
parameter. 第二步是绑定隐藏的
this
参数。 You can do this with std::bind
, which "attaches" parameter values to a function (or a method pointer). 您可以使用
std::bind
执行此操作,将参数值“附加”到函数(或方法指针)。 It returns an unspecified type that is known to be callable and known to be suitable for the construction of an std::function
. 它返回一个未指定的类型,该类型已知可调用且已知适合构造
std::function
。
startTimer(bind(&MainPage::read, this));
I was able to get this working by declaring read as a function rather than as a member of MainPage. 通过将read声明为函数而不是MainPage的成员,我能够实现这一点。
void read() {
...
}
It's not a perfect solution, but it's good enough for me. 这不是一个完美的解决方案,但它对我来说已经足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.