VariantConverter for enums

Hi all,

It would be great if JUCE would automatically implement a VariantConverter for enums as they are basically named integers and a conversion is therefore very straight forward using a static_cast.

With the new c++ 20 I think one should be able to take it up a notch and implement something like this:

template <typename _TEnum> requires std::is_enum<_TEnum>::value
struct VariantConverter
{
  static _TEnum fromVar(const var& v) { ... }
  static var    toVar(_TEnum enumValue) { ... }
};

But as the compiler correctly notices, this definition of VariantConverter does not match the forward declaration. But maybe someone more experienced with templates can get this to compile so that the compiler automatically matches this implementation for all enum types.

They’re basically named ints, is exactly why there shouldn’t be a built-in conversion for enums.

In some cases you may want to serialise the enums as their numerical value, while in others you may want to serialise them as their named value.

serializing with named values is often safer because then it would still work if the sequence of the entries is changed

To me it really depends on whether or not the value needs to be human-readable.

If you want to serialise/deserialise some data to an XML file that a user can manually edit for example, then you don’t want colour="2", you’d want colour="red".

Whereas if you want to optimise for the most compact serialisation, maybe you want to upload a huge amount of data to some server, then you’d want to numeric approach.

Point is, there’s no one right way to do it, and even within a single application you might want to treat the same enum differently in different cases.

There is a huge difference: If you change the enum adding a value, the code stays intact. But saved data would be corrupted, while when using the names there is a fair chance the saved data still works as expected.

When storing an enum as int it becomes a bunch of magic numbers.

But for a proper large storage one should prefer either a binary protocol like flatbuffers or write a proper XSD to the XML so it can be validated. But that hits the limits for JUCE’s XML functionality, not only ValueTree but also juce::XmlElement.