std :: function不起作用,但是普通的旧函数指针却起作用-为什么?

问题描述 投票:1回答:1

我想制作一个将std::function作为参数的函数,并在内部调用该函数:

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

和呼叫者(在同一个类中:)>

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

错误:

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

但是],如果我遵循C风格的函数指针:

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

然后它确实可以正常工作(呼叫者是相同的。)>

如何使std::function工作?旁注:我不想使任何内容静态化。

我想制作一个将std :: function作为参数的函数,并在内部传递通过函数的调用:void handleCollision(std :: function &resolveCollision,...

c++ pointers std function-pointers std-function
1个回答
0
投票
用lambda包装,替换

handleCollision(resolveCollisionAxisX, block)

© www.soinside.com 2019 - 2024. All rights reserved.