代码之家  ›  专栏  ›  技术社区  ›  Ð..

Boost HANA:将Hana Types转换为STD::

  •  2
  • Ð..  · 技术社区  · 6 年前

    是否存在用于编译时转换 结构 STD:STD的STL容器的概念:

    例如,

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

    将“int string bool”转换为stdout,

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

    文档清楚地提供了获取 结构 概念,但我还没有找到任何东西能帮你 成员类型 . 更简单的任务是:

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

    我读过 this post 但我想知道哈娜有没有一条干净的出路。更好的方法是遍历 结构 不用知道他们的名字。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Justin    6 年前

    如果使用clang,hana有一个实验特性 hana::experimental::type_name . 这可用于获取结构成员的类型名:

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

    演示(演示) 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';
        });
    }
    

    输出:

    int
    std::__1::basic_string<char>
    float
    
    推荐文章