[FR] Add a templated constructor to `juce::var` that uses `juce::VariantConverter` to construct the var

It’s really nice being able to implicitly construct a juce::var from types that it supports, e.g.

void setValue (juce::var value);

setValue ("Hello, World!");
setValue (123);

However, when you want to set a custom type for which you’ve specified a juce::VariantConverter, suddenly it’s not so nice:

struct MyCoolClass{};

template<>
struct VariantConverter<MyCoolClass> {};

setValue (juce::VariantConverter<MyCoolClass>::toVar (myCoolObject));

It’d be really nice if there were a templated constructor for juce::var that used juce::VariantConverter internally, and perhaps an operator T() as well?

template<typename T>
var::var (const T& value)
{
    *this = VariantConverter<T>::toVar (value);
}

template<typename T>
T var::operator T() const
{
    return VariantConverter<T>::fromVar (*this);
}

I was recently struggling with using VariantConverter in a similar situation.

Since it’s “MyCoolClass”, and you are free to modify it, you can accomplish the simplified syntax by providing your class with a ctor that takes a var, and an operator var() method that returns a var.

    explicit MyCoolClass (juce::var v);

    operator juce::var() const;
1 Like

Nice - I tend to use toVar() and fromVar() free functions now for wrapping the calls to juce::VariantConverter, and to specialise for primitive types so you don’t need to use different methods for different types.

Would still be nice to have something in JUCE to make conversions less verbose.

1 Like