Var(uint32 colourValue) not possible

Hi everybody,

I noticed that you can’t write something like this:

var colourValue(0xFF00FF00);

Apparently, 0xFF00FF00 is an unsigned int because it uses the full bit range (like any ARGB colour value) and there’s no constructor for the var object and the compiler goes crazy trying to decide whether to use var(int) or var(int64). Now you could obviously write

var colourValue(static_cast<int64>(0xFF00FF00));

but this is as ugly as it can get. So I wondered if an explicit constructor for uint32 values is a sensible addition to the var class, given the prime use case of it is UI stuff and I think you need colours for UI…

This would be the addition in juce_Variant.cpp - I’ll leave the addition in the header file as excercise for the more experienced coders out there :slight_smile:

var::var (const uint32 v) noexcept :	type (&VariantType_Int64::instance)  { value.int64Value = static_cast<int64>(v); }

PS: Why are the constructors in the .cpp file using const parameters and the header definitions don’t (at least for the most primitive types)? Not that it would make any difference, but it looks weird…

To answer your PS…

This is just common practice since the const has no meaning to the declaration of function arguments but the function body might want to explicitly prevent modification in its implementation to avoid errors.

I wrote a serializer/deserializer that converts std:: containers to and from ValueTrees and in the process of writing it, I too, ran into the issue of someUnsignedType val = ValueTree::getProperty() causing a couple different compiler errors:

conversion from 'const juce::var' to 'size_type' (aka 'unsigned long') is ambiguous
Ambiguous conversion for C-style cast from 'const juce::var' to 'unsigned char'

Why doesn’t the var class support unsigned types? how could support be added?

if it helps, here’s my usage:

    template< typename Container, typename Type >
    void ConvertToContainer(Container& container, const ValueTree& tree)
        jassert( (int)container.size() == tree.getNumChildren() );
        for( int i = 0; i < tree.getNumChildren(); ++i )
            //this doesn't work when Type is something other than int/int64/bool/float/double/string
            container[i] = (Type) tree.getChild(i).getProperty("value");

I solved it with this:

            if constexpr( std::is_unsigned<Type>::value )
                container[i] = (Type) tree.getChild(i).getProperty("value").operator int();
                container[i] = (Type) tree.getChild(i).getProperty("value");