🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Template Function

Started by
2 comments, last by Zapato 6 years ago

I'm implementing a Entity Component System in AngelScript, suppose we have the following classes


abstract class Component { }
class Position : Component { float x; float y; }
class Velocity : Component { float vel; }

Then we have an entity that holds Component objects, currently I'm associating a number to the components and doing the following to retrieve them.


Velocity@ vel = cast<Velocity>(entity.getComponent(VelocityIdx));

There is a way in AngelScript side to define a template function? I want to instead doing something like.


Velocity@ vel = entity.getComponent<Velocity>();

//or maybe something like
Velocity@ vel = entity.getComponent(Velocity.class);

Or there is any way to avoid casting each time when retrieving a component?

Thanks in advance.

Advertisement

It is possible, though not without some quirks and is not exactly straightforward. http://www.angelcode.com/angelscript/sdk/docs/manual/doc_adv_template.html

A different solution is to add a specific interface for each type.


// Template is longer to type
Velocity@ vel = entity.getComponent<Velocity>();

// than a specific inteface.
Velocity@ vel = entity.getVelocity();

 There's two advantages to that. First, once the interfaces are there, your code is easier to write because less characters to type every time. Second, it is by default a lot more efficient than templates because AngelScript templates are determined at runtime unless you override a template specialisation for each different type.  (see Template specializations in the link above).

Hey Michael, thanks for the reply, I knew about template classes registered on C++ but it has the overhead you said, also it's not exactly a template function by making the whole class a template. I like the second most, the interface solution, but I think it have some flaws too, the repeated code pattern still on it in some way, and also for every new component you have to modify the Entity class and the interface, so the design is not the best but maybe I have to settle with that. Thanks again Michael.

This topic is closed to new replies.

Advertisement