C++ - 设计问题
我正在开发游戏引擎原型,并有以下问题:
现在我的引擎实现是 DirectX 绑定的,一切正常。
我有一个 core::Renderer
类,它具有渲染几何体、设置着色器、闪电等的方法...
其中一些是模板化的,一些是模板化 的不。
class Renderer {
// ...
template <typename Geometry> RenderGeometry(shared_ptr<Geometry> geometry);
};
假设我想扩展引擎的灵活性,并且不希望它使用 DirectX 和 OpenGL 来工作。据我现在的理解,这个想法是将所有特定于接口的内容都放在 core::Renderer
基类中,使所有这些调用虚拟
,然后提供它们的DirectX 特定 和OpenGL 特定 实现。
如果我的几何对象不是模板,一切都会看起来更好:
class Renderer {
virtual void RenderGeometry(shared_ptr<core::Non_template_Geometry> geometry);
};
class DXRenderer {
// Here goes our custom implementation
// for DirectX-based geometry rendering
virtual void RenderGeometry(...)
};
// The same for OpenGL
第一个(初始变体)的问题是虚拟函数不允许模板化。
< strong>那么问题来了 - 我应该如何解决它?
对于这种情况或模板虚拟函数模拟有什么技巧/技巧/模式吗?
I am working on game engine prototype and have the following question:
Right now my engine implementation is DirectX-bound and everything works fine.
I've got a core::Renderer
class which has methods to render geometry, set shaders, lightning, etc...
Some of them are templated, some not.
class Renderer {
// ...
template <typename Geometry> RenderGeometry(shared_ptr<Geometry> geometry);
};
Let's say I want to extend the flexibility of my engine and I wan't it to work using DirectX and OpenGL. As I understand it right now, the idea is to take everything interface-specific to the base core::Renderer
class, make all those calls virtual
and then provide their DirectX-specific and OpenGL-specific implementation.
If my geometrical object wasn't a template, everything would look better:
class Renderer {
virtual void RenderGeometry(shared_ptr<core::Non_template_Geometry> geometry);
};
class DXRenderer {
// Here goes our custom implementation
// for DirectX-based geometry rendering
virtual void RenderGeometry(...)
};
// The same for OpenGL
The problem with the first (initial variant) is that virtual functions are not allowed to be templated.
So here comes the question - how should I solve it?
Any hacks / tricks / patterns for this situation or for template virtual functions emulation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模板不是必需品。如果你仔细想想,大多数时候模板只做文本替换,是一个更安全的宏。
OOP 的设计并不是严重依赖模板,而是组合和继承(就像 James 所建议的那样)
Template is not neccessity. If you think hard about it, most of the time templates only do text-replacing and is a safer macros.
OOP was not design to rely heavily on templates, but composition and inheritance (like what James suggested)
使用
Geometry
基类:让每个 Geometry 类型的类派生自该基类,并通过重写
Render
来实现其特定的渲染功能。那么,
Renderer::RenderGeometry
不需要是函数模板;它可以简单地获取一个指向基Geometry
类的指针并调用虚函数Render
。Use a base
Geometry
class:and have each of your Geometry-type classes derive from this base class and implement their specific rendering functionality by overriding
Render
.Then,
Renderer::RenderGeometry
does not need to be a function template; it can simply take a pointer to the baseGeometry
class and call the virtual functionRender
.