Search code examples
c++c++14unionsboost-hana

Are unions guaranteed to work with boost::hana::Structure?


Suppose I have this:

#include "boost/hana.hpp"


union Thing {
    BOOST_HANA_DEFINE_STRUCT(Thing,
        (long, m1),
        (int, m2)
    );
};

This currently works, but is there anything that guarantees that this will always work (that some future change won't make it so that this does not work)?


Solution

  • The documentation claims to support the use of the macro to define members within a "user-defined type" here, and since a union is technically a type of class, I'd say its safe to say that it is supported.

    That isn't to say that it will always be supported, but changing it would be a breaking change and probably require a new major version ie Boost.Hana 2.0.

    There are some other things about the Struct concept's associated interface that could be fixed, but I don't think that would affect this use case.

    If you want an authoritative answer from the author, perhaps an issue on Github would be the way to go.

    All of that said, keep in mind that Struct refines Comparable and Foldable which operate on the members in sequence which would be a bit odd for members of a union.

    It's a neat idea, and I'm interested in seeing what can be done with this.

    I expanded on your example:

    #define BOOST_HANA_CONFIG_ENABLE_STRING_UDL
    #include "boost/hana.hpp"
    
    namespace hana = boost::hana;
    using namespace boost::hana::literals;
    
    
    union Thing {
        BOOST_HANA_DEFINE_STRUCT(Thing,
            (long, m1),
            (int, m2)
        );
    };
    
    int main()
    {
      Thing thing{};
      hana::at_key(thing, "m2"_s) = 42;
    
      BOOST_HANA_RUNTIME_CHECK(thing.m2 == 42);
    }