Search code examples
c++pointersstdfunction-pointersstd-function

std::function does not work, but plain old function pointer does - why?


I want to make a function that will take std::function as a parameter, and inside call that passed function:

void handleCollision(std::function<void(const Entity&)>& resolveCollision, const Entity& block) {
    if (playerInRangeOf(block) && playerIntersects(block)) {
        resolveCollision(block);
    }
}

And the caller (within the same Class):

for (auto&& block : blocks) {
    handleCollision(resolveCollisionAxisX, block);
}

Error:

Reference to non-static member function must be called
error: no matching function for call to 'StateGame::handleCollision(<unresolved overloaded function type>, Block&)'
handleCollision(resolveCollisionAxisX, block);
                                            ^

However, if I follow with C-style function pointers:

void handleCollision(void (StateGame::*resolveCollision)(const Entity&), const Entity& block) {
    if (playerInRangeOf(block) && playerIntersects(block)) {
        (this->*resolveCollision)(block);
    }
}

Then it does work fine (caller is the same).

How can I make the std::function work? Side note: I don't want to make anything static.


Solution

  • Wrap it in a lambda, replace

    handleCollision(resolveCollisionAxisX, block)
    

    to

    [this](const Entity& e){
       this->resolveCollisionAxisX(e);
    }
    

    Also replace std::function<void(const Entity&)>& to std::function<void(const Entity&)> or const std::function<void(const Entity&)>&