假设我们有一个接口(interface) window_creator 负责创建窗口。为简单起见,它看起来像这样:
struct window_creator
{
virtual ~window_creator(){}
handle create_window(size_t width, size_t height, bool fullscreen);
};
此外,我们还有渲染系统接口(interface),负责在 window_creator 创建的窗口中进行渲染。为简单起见,它具有以下代码:
struct render_system
{
virtual ~render_system(){}
void create(handle window_handle);
};
此外,我们还有 2 个 window_creator 接口(interface)的实现:
struct windows7_creator : public window_creator
{
handle create_window(size_t width, size_t height, bool fullscreen) override {
//calls CreateWindow and returns HWND
}
};
struct macos_creator : public window_creator
{
handle create_window(size_t width, size_t height, bool fullscreen) override {
//calls createWindow_ and returns WindowRef
}
};
以及 render_system 接口(interface)的 2 个实现:
struct dx_render_system : public render_system
{
void create(handle window_handle) override{
//calls CreateDevice, etc...
}
};
struct opengl_render_system : public render_system
{
void create(handle window_handle) override{
//calls gl... etc...
}
};
现在在 Windows 平台上我可以创建 dx 或 OpenGL 渲染器。在 MacO 上,我可以创建 OpenGL 渲染器。 问题是:我应该创建什么类型的句柄来支持 window_creator 和 render_system 接口(interface)的独立性?
在我当前的实现中,我为句柄编写了 typedef:
typedef void* handle;
这个问题有没有更优雅的解决方案?
最佳答案
通常这种事情是用以下模式完成的:
#ifdef OS_IS_WINDOWS
#include "WindowsHandle.h"
typedef WindowsHandle NativeHandle;
#elif OS_IS_MAC
#include "MacHandle.h"
typedef MacHandle NativeHandle;
#elif OS_IS_FOO
#include "FooHandle.h"
typedef FooHandle NativeHandle;
#end
您不需要对不同的 NativeHandles 进行运行时分派(dispatch) - 事实上,在不牺牲类型安全的情况下,这几乎是不可能的 - 因为平台特定句柄的定义并非在每个平台上都可用。
您已经在编译时静态地知道您使用的是什么操作系统,因此您不妨利用这一点。
关于c++ - 通过窗口句柄连接的渲染和窗口系统的独立性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9934371/