2

Does there exist a Boost Hana method for compile-time converting the types of members of a Struct concept to a STL container of std::string's of the typenames?

For example,

MyType t();
std::array<std::string, 3> ls = boost::hana::typesToString(t);
for(std::string x : ls){
     std::cout << x << std::endl;
}

Yields "int string bool" to STDOUT,

With

class MyType{
     int x; 
     std::string y;
     bool z;
}

The documentation clearly provides methods for getting the members and their values of an instance of a Struct concept, but I haven't found anything there that does this for the types of the members. A simpler task would be to do:

 int x;
 std::string tName = boost::hana::typeId(x); //tName has value "int"

I've read this post but I'd like to know if there's a clean way out-of-the-box in Hana. Even better would be a way to iterate through the members of the Struct without having to know them by name.

Ð..
  • 298
  • 5
  • 18

1 Answers1

2

If you are using Clang, Hana has an experimental feature hana::experimental::type_name. This can be used to get the type-names of the members of the struct:

#include <boost/hana.hpp>
#include <boost/hana/experimental/type_name.hpp>

namespace hana = boost::hana;

template <typename Struct>
auto member_type_names() {
    constexpr auto accessors = hana::accessors<Struct>();

    return hana::transform(
        accessors,
        hana::compose(
            [](auto get) {
                using member_type
                    = std::decay_t<decltype(get(std::declval<Struct>()))>;

                return hana::experimental::type_name<member_type>();
            },
            hana::second
        )
    );
}

Demo (live on Wandbox):

#include <iostream>
#include <string>

struct MyType {
    int a;
    std::string b;
    float c;
};

BOOST_HANA_ADAPT_STRUCT(MyType, a, b, c);

int main() {
    hana::for_each(member_type_names<MyType>(), [](auto name) {
        // Note that the type of `name` is a hana::string, not a std::string
        std::cout << name.c_str() << '\n';
    });
}

Outputs:

int
std::__1::basic_string<char>
float
Justin
  • 24,288
  • 12
  • 92
  • 142