Template specialization in c++ - it really is useful
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.<p>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:<p>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).<p>So every property of every in-game object should keep old and new value, and should make it possible to interpolate between these values.<p>For this to work I wanted to do template class 
OldAndVewValue&#60;T&#62;, so in-game objects will keep its properties in such classes.<p>But OldAndNewValue should allow interpolating between these values at any t between 0.0f and 1.0f.<p>For numerical properties (int, float) it is easy - OldAndVewValue will just have method<p>T get(float t) {return _old * (1.0f-t) + _new * t; }<p>It will even work for position and velocity, because Vector class has operator+ and operator* defined.<p>But what about orientation that is a Quaternion - it has operator+ and operator<i>, but interpolating Quaternions that way will look wrong.<p>Or what about properties like
Weapon</i> activeWeapon;
etc?<p>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.<p>So I've written this prototype program and it worked (it uses std::string instead of Quaternion or Weapon* - just to show idea).<p>http://www.nopaste.pl/u01<p>It turns out template specialization will do just fine here, without making convulted class hierarchies, wrapping fields or anything.<p>Sometimes C++ is almost a expressive as hip functional languages.<p>Hope it helps someone with similar problem.