【问题标题】:Boost Hana : Convert Hana Types to std::string'sBoost Hana:将 Hana 类型转换为 std::string
【发布时间】:2018-05-30 19:08:30
【问题描述】:

是否存在用于在编译时将 Struct 概念的成员类型转换为类型名的 std::string 的 STL 容器的 Boost Hana 方法?

例如,

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

文档清楚地提供了获取 Struct 概念实例的成员及其值的方法,但我还没有找到任何对成员类型执行此操作的方法。一个更简单的任务是:

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

我已阅读 this post,但我想知道 Hana 中是否有一种开箱即用的干净方法。更好的方法是遍历 Struct 的成员,而不必知道它们的名称。

【问题讨论】:

    标签: c++ boost boost-hana


    【解决方案1】:

    如果您使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      相关资源
      最近更新 更多