" 尝试将函数作为参数传递时出错,c++"/>

首页 > 解决方案 > “不存在合适的构造函数来将“void ()”转换为“std::function”" 尝试将函数作为参数传递时出错

问题描述

我有一个输入类,它有一个应该将函数作为参数的方法。

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

我有一个应该调用该函数的三角形处理器类。

#include "pixelGameEngine.h"
#include "input.h"
#include <functional>
class TriangleProcessor
{
    //...
    void DoIteration() noexcept{};
    Input input;
    void Run(olc::PixelGameEngine* pge)
    {
        Input::OnDPress(pge, DoIteration);
    }
}

但是我在 .下方出现红色波浪"no suitable constructor exists to convert from "void () to "std::function<void ()>"线错误。Input::OnDPress(pge, DoIteration);DoIteration

标签: c++

解决方案


DoIteration不是函数。这是在TriangleProcessor类上定义的方法。std::function您尝试调用的常用构造函数用于std::function从可调用对象或函数指针生成实例。DoIteration有一个隐含的this论点。

现在,您在 内部运行Run它,它碰巧可以访问该隐含this参数。因此,在您的情况下,我们可能希望传递当前this值。我们能做到这一点

Input::OnDPress(pge, [this]() { this->DoIteration(); });

推荐阅读