I would like to store quantities such as weight, time, length. I suppose this way is more readable and avoid mismatch in such function:
Velocity computeSpeed(Distance d, Time t);
Currently I only have
using float_type = double;
using Velocity = float_type;
using Distance = float_type;
using Time = float_type;
However, for my application I need some conversions such as:
Distance toInches(Distance);
Distance toMillimeters(Distance);
I rather wanted to have something like:
Distance d;
std::cout << d.toInches();
However, overloading base types may have some drawbacks:
- It requires to overload all operators or use a CRTP on float type
- This may impact the efficiency
Is it possible to add "conversion" const methods to numeric types? Side question: is this approach bad or overkill?
NOTE: I am stuck with C++03 :(
I have done what you are trying to do in C#, which has far fewer overloading capabilities than C++. The result is awesome, since it protects you from all kinds of mistakes and keeps the code terse and to the point. (It eliminates incidental complexity.)
It also allows your IDE's completion suggestions feature to shine, because it will show you what you can do with each variable, instead of having to know by heart which global-scope functions are applicable to each variable.
The way to do it is to declare a new class for each different type of quantity, which contains a single value in some standard unit. (And you will, of course, choose the SI system for your standard units, right?)
Once you have these classes, you can overload all the applicable operators so that they work between instances of each class and between every combination that makes sense.
If you like living your life dangerously you can even use the amazing ability of C++ to overload the type-cast operator, so that you can directly assign
floatto an instance of a quantity, hoping (praying) that the float is in the right unit. My advice would be that you don't do that, and instead you create static methods likeLength::ofMeters( float ),Length::ofInches( float )etc.