Search code examples
c++boostboost-hana

Hana BOOST_HANA_DEFINE_STRUCT does not work with std::unique_ptr


Boost Hana's BOOST_HANA_DEFINE_STRUCT does not seem to work with std::unique_ptr as fields. Any workaround?

#include <boost/hana.hpp>
#include <memory>

struct Test
{
    BOOST_HANA_DEFINE_STRUCT(Test,
        (unsigned, field0),
        (std::unique_ptr<unsigned>, field1));
};

int main(int argc, char** argv)
{
    Test test;
    boost::hana::for_each(boost::hana::members(test), [&](auto field)
    {
    });

    return 0;
}

error: no matching constructor for initialization of 'tuple::type, typename detail::decay > &>::type>' (aka 'tuple > >') { return {static_cast(xs)...}; }


Solution

  • Yes, unfortunately, members makes a tuple where the values are copied when passed as an lvalue reference.

    You can use accessors or keys to get a reference to each member:

    #include <boost/hana.hpp>
    #include <memory>
    
    struct Test
    {
        BOOST_HANA_DEFINE_STRUCT(Test,
            (unsigned, field0),
            (std::unique_ptr<unsigned>, field1));
    };
    
    int main(int argc, char** argv)
    {
        Test test;
        boost::hana::for_each(boost::hana::keys(test), [&](auto key)
        {
          auto& field = boost::hana::at_key(test, key);
        });
    
        return 0;
    }