Search code examples
c++templatesvirtual

C++ - design question


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?


Solution

  • Use a base Geometry class:

    class Geometry {
    public:
        virtual ~Geometry() { }
        virtual void Render() = 0;
    };
    

    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 base Geometry class and call the virtual function Render.