How to handle units in c++ interface

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

    I prefer the solution from Anders K, however you may use a template to save some time implementing all units as a separte class which can be timeconsuming and prone to errors as you may need to write a lot of code by hand:

    enum Unit {
        MILI_VOLT = -3,
        VOLT = 0,
        KILO_VOLT = 3
    };
    
    class PowerMeter
    {
    public:
    
        template
        void ForceVoltage(double val)
        {
            std::cout << val * pow(10.0, N) << endl;
        };
    };
    

    Use like this:

            PowerMeter pm;
            pm.ForceVoltage(1);
            pm.ForceVoltage(1);
            pm.ForceVoltage(1);
    

提交回复
热议问题