std::list containing std::function

对着背影说爱祢 提交于 2020-01-02 10:25:19

问题


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


回答1:


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);




回答2:


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();
}


来源:https://stackoverflow.com/questions/19734818/stdlist-containing-stdfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!