c++ - 将成员函数指针设置为空闲函数指针

标签 c++ pointers function-pointers member-function-pointers

我正在开发一个用 c++ 编码并用 ctypes 包装的简单引擎。我正在研究窗口类,我想让引擎用户能够设置绘制和更新功能。我有以下代码:
窗口.h

#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
class window
{
public:
    GLFWwindow* wnd;

    window(int width, int height, const char* title);
    void close();

    void update();
    void (window::*draw)();

    void setDrawFunction(void (window::*)());
    void setUpdateFunction(int*);
};
窗口.cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include "window.h"

void default_draw() {
    glClear(GL_COLOR_BUFFER_BIT);
}

void default_update() {
    
}

window::window(int width, int height, const char* title)
{
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_COMPAT_PROFILE, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    wnd = glfwCreateWindow(width, height, title, NULL, NULL);

    if (wnd == NULL) { glfwTerminate(); return; }

    glfwMakeContextCurrent(wnd);

    if (glewInit() != GLEW_OK) {
        glfwTerminate();
        return;
    }

    setDrawFunction((void)(window::*)()default_draw);
}

void window::close() {
    glfwDestroyWindow(this->wnd);
}

void window::update() {
    default_update();
}

void window::setDrawFunction(void (window::*fnptr)()) {
    draw = fnptr;
}
这行不通。我是否遗漏了一些明显的东西,或者不可能以这种方式完成。如果是这样,我有什么办法可以做到这一点?我所需要的就是能够超速驱动功能,所以我可以在 python 中使用 ctypes 来做到这一点。
我得到的错误:
109 调用前的表达式必须有函数(指针)类型
29 表达式预期
18 预期“)”

最佳答案

window的成员函数指针的使用作为成员变量是不合适的。
我可以想到以下选项来解决这个问题。
选项1
制作 draw非成员函数指针。

void (*draw)();

void setDrawFunction(void (*func)());
选项 2
制作 draw一个 std::function
std::function<void()> draw;

void setDrawFunction(std::function<void()> func);
选项 3
使用单独的类/接口(interface)进行绘图。
std::unique_ptr<DrawingAgent> draw;

void setDrawingAgent(std::unique_ptr<DrawingAgent> agent);
在哪里
class DrawingAgent
{
   public:
      virtual void draw(window*); // Draw in given window.
};

在上述选项中,我建议使用 选项 3 .它将应用程序的窗口方面与绘图功能清晰地分开。

关于c++ - 将成员函数指针设置为空闲函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63268941/

相关文章:

C:如何访问存储在空指针(void *)中的函数指针?

c++ - 使用指向成员的指针将成员函数作为参数传递

c++ - [] 在 C++ 中的奇怪用法。怎么了?

C++ 添加linux用户

连接两个字符数组 C

c - 在结构中填充字符指针

c++ - 具有恒定时间访问任何元素的容器,从前面弹出并向后推?

c++ - 实例与新实例热交换自身

c++ - 将指针数组作为空指针传递给 C++ 中的新线程

在 C 中转换函数指针返回类型