# \[FR\] Add support for enum and enum class in juce::var

**URL:** <https://forum.juce.com/t/fr-add-support-for-enum-and-enum-class-in-juce-var/52553>\
**Category:** Feature Requests\
**Created:** [August 10, 2022, 1:56pm UTC](https://forum.juce.com/t/fr-add-support-for-enum-and-enum-class-in-juce-var/52553 "2022-08-10T13:56:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![baremetaldev](https://avatars.discourse-cdn.com/v4/letter/b/9fc29f/32.png) [@baremetaldev](https://forum.juce.com/u/baremetaldev)\
**Post date:** [August 10, 2022, 1:56pm UTC](https://forum.juce.com/t/fr-add-support-for-enum-and-enum-class-in-juce-var/52553/1 "2022-08-10T13:56:36Z")

</div>

With a very small change, it is possible to support `enum` and `enum class` types in a `juce::var`.

In juce\_Variant.h

```auto
template <typename Type>
struct VariantConverter
{
    static Type fromVar (const var& v) { return static_cast<Type> (v); }
    static var toVar (const Type& t) { return t; }
};

```

can be changed to (note the extra defaulted template parameter):

```auto
template <typename Type, typename = void>
struct VariantConverter
{
    static Type fromVar (const var& v) { return static_cast<Type> (v); }
    static var toVar (const Type& t) { return t; }
};

```

This would then allow - either built into juce (as in the case of juce::String) or added by the user/developer like any other custom variant converter:

```auto
template<typename EnumType>
struct juce::VariantConverter<EnumType, typename std::enable_if_t<std::is_enum_v<EnumType>>>
{
    static EnumType fromVar(const juce::var& v)
    {
        return static_cast<EnumType>(static_cast<int>(v));
    }

    static juce::var toVar (const EnumType& e)
    {
        return static_cast<int>(e);
    }
};

```

At which point you can then use any `enum` and `enum class` in a `juce::var` without writing specific converters, e.g:

```auto
enum class EnumClassType { zero, one, two, three };
enum EnumType { four = 4, five };

auto enumClassValue = EnumClassType::two;
auto enumValue = EnumType::five;

auto enumClassVar = juce::VariantConverter<EnumClassType>::toVar (enumClassValue);

auto enumVar = juce::VariantConverter<EnumType>::toVar (enumValue);

```

I thought I’d share this as it may be something we’d like to get added to juce.

---

<div class="post-metadata">

**Author:** ![jrlanglois](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/jrlanglois/32/21372_2.png) [@jrlanglois](https://forum.juce.com/u/jrlanglois)\
**Post date:** [August 10, 2022, 7:38pm UTC](https://forum.juce.com/t/fr-add-support-for-enum-and-enum-class-in-juce-var/52553/2 "2022-08-10T19:38:06Z")

</div>

> `static_cast<int>(v)`

That wouldn’t work if the enum class is of type int64. Either you store everything as int64 to give yourself the max headroom, or you’d have to figure out if the underlying type is int32 or int64 (using `std::underlying_type` and some other trickery).
