简体   繁体   中英

Passing a function as a parameter to another function C++

I am trying to pass my function called read into another function called 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++.

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 . 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.

The second step is to bind the hidden this parameter. You can do this with std::bind , which "attaches" parameter values to a function (or a method pointer). It returns an unspecified type that is known to be callable and known to be suitable for the construction of an std::function .

startTimer(bind(&MainPage::read, this));

ideone example

I was able to get this working by declaring read as a function rather than as a member of MainPage.

void read() {
    ...
}

It's not a perfect solution, but it's good enough for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM