How to handle units in c++ interface

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

    Take a look at Boost.Units. Here's some example code:

    quantity
    work(const quantity& F, const quantity& dx)
    {
        return F * dx; // Defines the relation: work = force * distance.
    }
    
    ...
    
    /// Test calculation of work.
    quantity     F(2.0 * newton); // Define a quantity of force.
    quantity    dx(2.0 * meter); // and a distance,
    quantity    E(work(F,dx));  // and calculate the work done.
    

提交回复
热议问题