我有一个输入类,它有一个应该以函数作为参数的方法。
#include "pixelGameEngine.h"
#include <functional>
class Input
{
public:
Input() = default;
Input(const Input&) = delete;
Input& operator=(const Input&) = delete;
public:
static void OnDPress(olc::PixelGameEngine* pge, std::function<void()> DoIteration) noexcept
{
if (pge->GetKey(olc::D).bPressed)
{
DoIteration();
}
}
};
Run Code Online (Sandbox Code Playgroud)
我有一个三角形处理器类应该调用该函数。
#include "pixelGameEngine.h"
#include "input.h"
#include <functional>
class TriangleProcessor
{
//...
void DoIteration() noexcept{};
Input input;
void Run(olc::PixelGameEngine* pge)
{
Input::OnDPress(pge, DoIteration);
}
}
Run Code Online (Sandbox Code Playgroud)
但我"no suitable constructor exists to convert from "void () to "std::function<void ()>"在网上遇到了一个错误Input::OnDPress(pge, DoIteration);,下面有一个红色的波浪线DoIteration。
DoIteration不是一个函数。它是在类上定义的方法TriangleProcessor。std::function您尝试调用的常用构造函数用于std::function从可调用对象或函数指针生成实例。DoIteration有一个隐含的this论点。
现在,您在 的内部运行它Run,它恰好可以访问该隐含this参数。因此,就您而言,我们可能希望传递当前this值。我们能做到这一点
Input::OnDPress(pge, [this]() { this->DoIteration(); });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4038 次 |
| 最近记录: |