Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22814

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?

Upvotes: 0

Views: 166

Answers (2)

kizzx2
kizzx2

Reputation: 19213

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)

Upvotes: 1

James McNellis
James McNellis

Reputation: 355039

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.

Upvotes: 2

Related Questions