I have some enum classes for units, like Weight units (KG and LB). I am translating the code to Qt C++ from Java, and I'm wondering what the best way to do this is as enums cannot have constructors in C++ that same way they do in Java (as far as I know).
Here is the Java class:
public enum WeightUnit { LB(WEIGHT_UNIT_LB, 0.45359237), //"lb" 1lb = 0.45359237 kg. KG(WEIGHT_UNIT_KG, 1.0); //"kg" private String displayName; private double scale; private WeightUnit(String displayNameKey, double scale) { this.displayName = getDataMessages().getString(displayNameKey); this.scale = scale; } public String getDisplayName() { return displayName; } public String toString() { return displayName; } public static WeightUnit valueByName(String unitName) { for (WeightUnit value : WeightUnit.values()) { if (value.getDisplayName().equals(unitName) || value.name().equals(unitName)) { return value; } } throw new IllegalArgumentException(unitName); } public static double convert(double value, WeightUnit from, WeightUnit to) { if (from == to) return value; return value * from.scale/to.scale; } }
Here is my C++ translation. It is not as elegant or clean as the Java version.
class WeightUnit {
public:
enum Value
{
LB,
KG
};
WeightUnit() = default;
constexpr WeightUnit(Value weightUnit) : value(weightUnit) {}
bool operator==(WeightUnit a) const { return value == a.value; }
bool operator!=(WeightUnit a) const { return value != a.value; }
static double convert(double value, WeightUnit fromUnit, WeightUnit toUnit){
return value * val(fromUnit.value)/val(toUnit.value);
}
static WeightUnit fromStr(QString str){
if (str.compare(toStr(Value::LB)) == 0)
return WeightUnit::LB;
else if (str.compare(toStr(Value::KG)) == 0)
return WeightUnit::KG;
else
throw QException();
}
static QString toStr(WeightUnit unit){
if (unit == WeightUnit::LB)
return "lb";
else if (unit == WeightUnit::KG)
return "kg";
else
throw QException();
}
private:
Value value;
static double val(Value value){
switch(value){
case KG:
return 1.0;
case LB:
return 0.45359237; //1 lb = 0.45359237 kg
}
throw QException(); //if not found, throw exception
}
};
Is there any better way to tie values to each enum value in C++? In Java it is easy, because you can specify a constructor that requires certain parameters so you can be sure each enum value has an appropriate String and double value. Is there a way to do this in Qt/C++?