How to handle units in c++ interface

前端 未结 9 2124
独厮守ぢ
独厮守ぢ 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:42

    how about instead turning it around a bit by creating classes (ms,mV) for the different currents

    e.g.

    PowerMeter.forceVoltage( mV(1) );  
    PowerMeter.settlingTime( ms(1) )
    

    It is pretty clear to the user and arguably not hard to read plus you would get type checking for free. having a common base class for the different units would make it easier to implement.

提交回复
热议问题