c++boostboost-hana

How to get the number of fields in a boost-hana adapted struct?


Say I have the following struct:

struct MyStruct
{
    int field1;
    float field2;
};

I would like to obtain the number of fields in the struct using boost-hana.

#include <boost/hana/adapt_struct.hpp>


BOOST_HANA_ADAPT_STRUCT(MyStruct, position, field1, field2);

// this code does not work:
constexpr std::size_t NUMBER_OF_FIELDS = boost::hana::length<MyStruct>();

static_assert(NUMBER_OF_FIELDS  == 2);

How to get the number of fields in a boost-hana adapted struct?


Solution

  • Hana specifically aims to simplify meta-programming by lifting type functions to the constexpr domain. In plain English: you shouldn't be using length<> as a "type function template" but as a normal function:

    Live On Coliru

    struct MyStruct
    {
        int position;
        int field1;
        float field2;
    };
    
    #include <boost/hana.hpp>
    
    BOOST_HANA_ADAPT_STRUCT(MyStruct, position, field1, field2);
    
    constexpr std::size_t NUMBER_OF_FIELDS = boost::hana::size(MyStruct{});
    static_assert(NUMBER_OF_FIELDS  == 3);
    
    int main(){}