我很想对我正在尝试的这个模板设计理念发表评论
我一直在教授游戏编程,并且花了很多时间讨论打破依赖关系,目标是如果引入新代码,旧代码不应更改。我们正在设置一个渲染器对象,我决定将渲染函数模板化,这样我就可以展示特征类等的一些用途。但这引发了一个有趣的想法。
如果我从不提供通用主体而只提供完整的专业化,那么渲染类可以根据它可以从外部代码渲染的内容进行扩展,并且如果渲染的对象没有完全专业化,则编译器会失败,而不是exe会失败。这使得使用该系统的游戏有机会构建自定义可渲染对象并扩展功能,而无需更改渲染器 hpp 或 cpp 文件。
这是一个已知的设计模式,还是一个糟糕的想法,为什么,或者有其他人这样做过吗?我很想知道这里是否存在严重问题,因为我看到的都是积极的一面。
谢谢大家。
这是格式化的代码。
我做的有点不同,所以客户端代码不知道它是一个模板。
class Renderer
{
public:
void SwapBuffers();
template<typename RenderObj>
void Render(const RenderObj&);
};
// Full specializations
class Sprite;
template<> void Renderer::Render<Sprite>(const Sprite&);
I've been teaching game programming and I've spent a lot of time talking about breaking dependencies with the goal that old code should not change if new code is introduced. We were setting up a renderer object and I decided to templatize the render function so I could show some uses for traits classes, etc. But this led to an interesting idea.
If I never provide a generic body and only provide full specializations then the render class can be extended regarding what it can render from outside code and if an object is rendered that does not have full specialization, the compiler fails rather than the exe. This allows games using this system a chance to build custom renderable objects and extend the functionality without needing to change the renderer hpp or cpp files.
Is this a known design pattern, or is it a terrible idea and why, or has anyone else done this? I'd love to know if there is a serious problem here because all I see are positives.
Thanks all.
Here's the code formated.
I'm doing it a little different so client code doesn't know it's a template.
class Renderer
{
public:
void SwapBuffers();
template<typename RenderObj>
void Render(const RenderObj&);
};
// Full specializations
class Sprite;
template<> void Renderer::Render<Sprite>(const Sprite&);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解您的描述:
我认为这是一种有效的方法。有时您可以填写一般案例主模板,有时则不能。指示您何时不能的编译时错误优于运行时错误(正如您所说)。
我想说设计模式是已知的,尽管我无法命名它。 C++11 中的 std::function 遵循类似的模式,尽管客户端通常不提供专门化(尽管理论上可以):
If I'm correctly understanding your description:
I consider this a valid approach. Sometimes you can fill out the general case primary template, and sometimes you can't. And a compile time error to indicate when you can't is superior to a run time error (as you said).
I would say the design pattern is known, though I can't put a name to it. std::function in C++11 follows a similar pattern, although clients don't usually supply a specialization (though theoretically could):