How to handle units in c++ interface

c++

Solution

I prefer avoiding macros where ever I can, and this is an example where it should be possible. One lightweight solution that gives you correct dimensions would be:

static double m = 1;
static double cm = 0.1;
static double mV = 0.001;

double distance = 10*m + 10*cm;

This also reflects the physical concept that units are something that's multiplied with the value.

Problem

I am currently designing an API where I want that the user to be able to write code like this: ``` PowerMeter.forceVoltage(1 mV); PowerMeter.settlingTime(1 ms); ``` Currently we do this using defines like: ``` #define mV *1.0e-03 ``` This makes it very convenient for the user to write their code and it is also very readable, but of course has also drawbacks: ``` int ms; ``` Will throw some compiler errors which are hard to understand. So I am looking for a better solution. I tried the new C++11 literals, but with this all I could achieve is: ``` long double operator "" _mV(long double value) { return value * 1e-3; } PowerMeter.forceVoltage(1_mV); ``` In the end the API does not care about the unit like Volt or second but only takes the number, so I don't want to do any checking if you really input Volts in forceVoltage or not. So this should also be possible: ``` PowerMeter.forceVoltage(2 ms); ``` Any idea besides staying with the defines?

Original source