开发者

I'd love comments on this template design idea I'm playing around with

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 i开发者_如何学编程s 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&);


If I'm correctly understanding your description:

template <class> class render; // undefined

template <>
class render<Object1>
{
   // ...
};

template <>
class render<Object2>
{
   // ...
};

// ...

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):

template <class> class function; // undefined

template<class R, class... ArgTypes>
class function<R(ArgTypes...)>
{
  // ...
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜