[英]Set member function pointer to free function pointer
我正在研究一个用 c++ 编码并用 ctypes 包装的简单引擎。 我正在研究 window class,我想让引擎用户能够设置绘制和更新功能。 我有以下代码:
window.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*);
};
window.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;
}
这行不通。 我是否遗漏了一些明显的东西,或者不可能以这种方式完成。 如果是这样,我有什么办法可以做到这一点? 我所需要的只是能够超速 function,所以我可以在 python 中使用 ctypes 执行此操作。
我得到的错误:调用前的 109 表达式必须有 function(指针)类型 29 表达式预期 18 预期“)”
将 window 的成员window
指针用作成员变量是不合适的。
我可以想到以下选项来解决这个问题。
draw
一个非成员 function 指针。
void (*draw)();
void setDrawFunction(void (*func)());
draw
一个std::function
std::function<void()> draw;
void setDrawFunction(std::function<void()> func);
使用单独的类/接口进行绘图。
std::unique_ptr<DrawingAgent> draw;
void setDrawingAgent(std::unique_ptr<DrawingAgent> agent);
在哪里
class DrawingAgent
{
public:
virtual void draw(window*); // Draw in given window.
};
在上述选项中,我建议使用Option 3 。 它将应用程序的window方面与绘图功能完全分开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.