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