How to handle units in c++ interface

前端 未结 9 2121
独厮守ぢ
独厮守ぢ 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 03:33

    Consider using an enum for your units and pass it as a second parameter:

    namespace Units
    {
        enum Voltage
        {
            millivolts = -3,
            volts = 0,
            kilovolts = 3
        };
    
        enum Time
        {
            microseconds = -6,
            milliseconds = -3,
            seconds = 0
        };
    }
    
    class PowerMeter
    {
    public:
        void forceVoltage(float baseValue, Units::Voltage unit)
        {
             float value = baseValue * std::pow(10, unit);
             std::cout << "Voltage forced to " << value << " Volts\n";
        }
    
        void settlingTime(float baseValue, Units::Time unit)
        {
             float value = baseValue * std::pow(10, unit);
             std::cout << "Settling time set to " << value << " seconds\n";
        }
    }
    
    int main()
    {
        using namespace Units;
        PowerMeter meter;
        meter.settlingTime(1.2, seconds);
        meter.forceVoltage(666, kilovolts);
        meter.forceVoltage(3.4, milliseconds); // Compiler Error
    }
    

    Wrapping the Units namespace around the enums avoids polluting the global namespace with the unit names. Using enums in this way also enforces at compile time that the proper physical unit is passed to the member functions.

提交回复
热议问题