I wanted to code a measurement unit conversion code to aid me to convert radians to degrees, metres to kilometres, etc.
I didn't want to polute the code with macros or such so I tried to implement it using metaprogramming.
I defined some basic template classes like BaseUnit and DerivedUnit.
Both take HeldType typename parameter. However DerivedUnit needs some kind of ratio so it's able to convert itself to BaseUnit.
DerivedUnit has operator BaseUnit() so it can be converted to it.
Both BaseUnit and DerivedUnit can be explicitly set to their HeldTypes (floats, doubles, whatever)
You know, then could just:
typedef BaseUnit\ Meter;
typedef DerivedUnit\ Kilometer;
// this is just for simplicity sake, you would have to inherit your units to avoid implicit conversions between various BaseUnits of same HeldType
void something( const Meter& v )
// do something
doSomething( Kilometer( 2.0 ) );
// the operator Meter() in Kilometer (auto instantiated using templates would convert it to Meter with no problems).
This all would work as long as I won't need any floating point ratio (metres, kilometres, megametres, whatever just use unsigned int ratios). But in fact I need floating point ratios very much (radians vs degrees most notably).
I want to do things like:
typedef DerivedUnit\ Degree;
However ISO C++ deprecated floating point template arguments I don't know why, I searched internet, mailgroups. It doesn't seem to be very old change, and noone is missing the feature. There must be some more elegant workaround.
First I though about nominator, denominator solution, however that seems very nasty and unelegant.
EDIT: Forgot to say, my target is gcc 4.1, no need to care about Visual Studio 6.0 or so. It would be great if it worked in newest Visual Studio and if it was ISO C++ compliant.