简体   繁体   中英

std::list containing std::function

What I'm trying to achieve is std::list that contains std::functions . I'm trying to implement a callback system where functions can be added to the list and then the list can be looped through and each function called.

What I have in class A is:

std::list<std::function<void( bool )>> m_callbacks_forward;

bool registerForward( std::function<void(bool)> f ) { m_callbacks_forward.push_back ( f ); return true; };

void GameControllerHub::invokeForward( bool state ) {

    for( std::list<std::function<void(bool)>>::iterator f = m_callbacks_forward.begin(); f != m_callbacks_forward.end(); ++f ){

        f();
    }

}

And then in class B

std::function<void(bool)> f_move_forward = [=](bool state) {
        this->moveForward(state);
    };

    getGameController()->registerForward ( f_move_forward );

...

bool Player::moveForward( bool state ) {
...
}

But in GameControllerHub::invokeForward I get error

"type 'std::list >::iterator' (aka '__list_iterator') does not provide a call operator"

I'm compiling with Xcode

You need to dereference the iterator to get the element it referes to. The iterator itself doesn't have operator() .

Write (*f)(state); or, if you wish, f->operator()(state);

You have to get the function element from the iterator before calling with * . Think of it like a sort of "pointer" to the desired value (the std::function object), you have to "dereference" it:

for( std::list<std::function<void(bool)>>::iterator f = m_callbacks_forward.begin(); f != m_callbacks_forward.end(); ++f ){
    (*f)();
}

By the way, if you can use C++11, then take advantage of the for-each loop:

for (std::function<void(bool)> f: m_callbacks_forward) {
    f();
}

or even more concise with auto :

for (auto f: m_callbacks_forward) {
    f();
}

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