Boost Hana : Convert Hana Types to std::string's

我是研究僧i 提交于 2019-12-24 01:17:22

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/50611863/boost-hana-convert-hana-types-to-stdstrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!