Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Template specialization in c++ - it really is useful
2 points by ajuc on Oct 19, 2010 | hide | past | favorite
I always tried to stay away from templates in C++. I knew a little about how it works, but it seemed to me it's rarely useful in regular (non-library) code, and makes debugging pain, so why bother.

Today I've wrestled with problem that has simple and (IMHO) elegant solution using template specialization, it was surprising for me that it is so simple and just works. So here it is:

In my game I need a way to interpolate between two given frames of game world - physic thread computes next frame at 30 Hz, and graphic thread draw some interpolation between last 2 frames as many times as it can (or at screen refresh frequency, if it can).

So every property of every in-game object should keep old and new value, and should make it possible to interpolate between these values.

For this to work I wanted to do template class OldAndVewValue<T>, so in-game objects will keep its properties in such classes.

But OldAndNewValue should allow interpolating between these values at any t between 0.0f and 1.0f.

For numerical properties (int, float) it is easy - OldAndVewValue will just have method

T get(float t) {return _old * (1.0f-t) + _new * t; }

It will even work for position and velocity, because Vector class has operator+ and operator* defined.

But what about orientation that is a Quaternion - it has operator+ and operator, but interpolating Quaternions that way will look wrong.

Or what about properties like Weapon activeWeapon; etc?

I've started thinking about making class heirarchy: BaseOldAndNewValue, NumericalOldAndNewValue, WeaponOldAndNewValue, QuaternionOldAndNewValue, etc, etc, and making virtual methods in them. But it seemed ugly, and I'm lazy.

So I've written this prototype program and it worked (it uses std::string instead of Quaternion or Weapon* - just to show idea).

http://www.nopaste.pl/u01

It turns out template specialization will do just fine here, without making convulted class hierarchies, wrapping fields or anything.

Sometimes C++ is almost a expressive as hip functional languages.

Hope it helps someone with similar problem.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: