且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Boost Hana:将Hana类型转换为std :: string的

更新时间:2023-02-20 09:43:20

如果您使用的是Clang,Hana具有实验功能

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
        )
    );
}

演示(生活在魔盒中):

#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';
    });
}

输出:

int
std::__1::basic_string<char>
float