How to handle units in c++ interface

前端 未结 9 2139
独厮守ぢ
独厮守ぢ 2021-02-07 02:56

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);
         


        
9条回答
  •  灰色年华
    2021-02-07 03:27

    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.

提交回复
热议问题