wc-duck / datalibrary

Open Source Data Library for data serialization.
Other
42 stars 8 forks source link

Generate accessors for union-types in headers? #51

Open wc-duck opened 8 years ago

wc-duck commented 8 years ago

Investigate if it is a good idea to, when compiling as c++, add, optional to use, accessors for union types to get and set members.

something like:


    enum my_union_type
    {
        my_union_type_item1 = ...;
        my_union_type_item2 = ...;
    };

    struct my_union
    {
        union
        {
            int32_t item1;
            struct apa item2;
        } value;
        my_union_type_item1 type;

       // things above is already generated.

        int32_t& item1()
        {
            ASSERT( type == my_union_type_item1 );
            return value.item1;
        }

        int32_t& as_item1()
        {
            type = my_union_type_item1;
            return value.item1;
        }

        struct apa& item2()
        {
            ASSERT( type == my_union_type_item2 );
            return value.item2;
        }

        int32_t& as_item2()
        {
            type = my_union_type_item2;
            return value.item2;
        }
    };

Biggest questions:

lundmark commented 7 years ago

To be honest, thinking about this for a while - I would be fine without the functions tbh. But you can also require that the user optionally can define their own DL_ASSERT, and if it isn't defined then just include assert.h and use the standard one.

wc-duck commented 7 years ago

One problem with generating the above helpers is that if the union-member is an array, I really have no type to return since arrays are just anonymous structs right now.

wc-duck commented 7 years ago

i.e. if you have

struct my_union
{
    union
    {
        struct
        {
            int32_t* data;
            uint32_t count;
        } int_array;
    } value;

    ????& as_int_array()
    {
        type = ...;
        return value.int_array;
    }
}
wc-duck commented 7 years ago

However if it could be done it could, in conjunction with a helper set( uint32_t count, type_ptr* data ) for arrays, shorten some code considerably.

take the above struct, where initialization would go from:

int32_t data[] = {1,2,3};
my_union m;
m.type = my_union_type_int_array;
m.value.count = 3;
m.value.data = data;

to

int32_t data[] = {1,2,3};
my_union m;
m.as_int_array().set( 3, data );