Template and component system

This week we started a new course called Game Programming III and during the lectures this week we learned about templates, linked lists and binary search tree, but the thing I am going to write about today is templates.

Templates are a method for creating generic functions or classes, and what I mean by generic is that they are type independent. You can use them for integers, floating-point numbers, Booleans etcetera, meaning that the function or the class can be reused instead of writing new classes or functions for every data type.

By using templates I wanted to create a basic Entity Component system, and for those who do not know what a component system is I recommend to read this chapter: http://gameprogrammingpatterns.com/component.html or rather I recommend you to read it all if you already have not because it is a very insightful book.

In short the component system is a way to create entities by adding different components to them, and this way the components only know about themselves and do not care about anything else than themselves. This meant that there was not unnecessary coupling between the classes.

At first templates does not seem to fit in here, but when you lay it down it becomes apparent that system resolves around templates.

Let us say that the object can have a physics component, a rendering component, a sound component, a input component and a Script component. If we do not use templates we would need a GetFunction for all of these different components and we would need to create a new GetFunction for every new component, making the Entity container a big nest of GetFunctions. So to negate this we create a template GetFunction which returns a template pointer, so that the return can be safeguarded if it returns a null pointer.

 

By using a base class for the components (Component) we can store all the components in the same map with an identifier as either a string or an enum.

Templates Component

 

In the picture is the game objects GetComponent function and below that is a call for the function. You specify what kind of component you want between the < > signs and then call for the appropriate key (in this example RENDERINGCOMPONENT). Then the function can convert the component to the correct type by using a static_cast.

I am really interested to see how templates can be used further, they have great capabilities when it comes to reuse code and making the code more generic.

If you are inexperienced with templates I recommend you to read more about it as there is a lot of material on the internet about it. Here is something to get you started:

http://www.cplusplus.com/doc/tutorial/functions2/

That was all from me for the time being, if you have questions or thoughts about the topic leave a comment.