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
解决方案
DoIteration
不是函数。这是在TriangleProcessor
类上定义的方法。std::function
您尝试调用的常用构造函数用于std::function
从可调用对象或函数指针生成实例。DoIteration
有一个隐含的this
论点。
现在,您在 内部运行Run
它,它碰巧可以访问该隐含this
参数。因此,在您的情况下,我们可能希望传递当前this
值。我们能做到这一点
Input::OnDPress(pge, [this]() { this->DoIteration(); });
推荐阅读
- jquery - 多个嵌套列表项的Jquery切换不起作用
- r - dplyr 加入列未出现
- java - 规则参数和规则返回值;antlr4 中的替代方案是什么?
- c - 在 C 中调用“线程入口点”函数作为“普通”函数是一种不好的代码实践吗?
- javascript - 无法使用 JavaScript 延迟 Youtube CSS
- javascript - 如何创建一个 interactivs JS (vanilla) 背景动画
- javascript - 从 adobe edge 阶段更改符号内的文本
- angular - 等到未知数量的 observables 完成
- c# - 如何管理跨平台应用程序中的图像?
- javascript - React服务器端渲染不输出索引页面