【问题标题】:Accessing the types of a tuple_t访问 tuple_t 的类型
【发布时间】:2016-03-22 13:26:46
【问题描述】:

我有这个代码:

auto myTuple = hana::tuple_t<int, char*, long>;
std::cout << boost::typeindex::type_id<decltype(myTuple[1_c])>().pretty_name() << std::endl;

这个输出:

boost::hana::type_impl<char*>::_

我想访问 'char*' 类型,但如果我这样做:

std::cout << boost::typeindex::type_id<decltype(myTuple[1_c])::type>().pretty_name() << std::endl;

它输出:

error: 'decltype(myTuple[1_c])' (aka 'boost::hana::type_impl<char *>::_ &') is not a class, namespace, or scoped enumeration
std::cout << boost::typeindex::type_id<decltype(myTuple[1_c])::type>().pretty_name() << std::endl

这是因为它是一个参考,如果我这样做:

std::cout << boost::typeindex::type_id<decltype(boost::hana::traits::remove_reference(myTuple[1_c]))::type>().pretty_name() << std::endl;

然后输出'char*'。

这是访问 tuple_t 类型的方法吗?必须有不那么繁琐的方法。

【问题讨论】:

    标签: c++ boost boost-hana


    【解决方案1】:

    这确实很棘手。 Hana 在 hana::type 上提供了一个一元加运算符,它将任何 ref 限定的 hana::type 衰减为一个右值。所以基本上,

    #include <boost/hana.hpp>
    namespace hana = boost::hana;
    using namespace hana::literals;
    
    auto myTuple = hana::tuple_t<int, char*, long>;
    using T = decltype(+myTuple[1_c])::type;
    //                 ^~~~~ notice unary plus here
    

    另请注意,您可能有兴趣使用来自&lt;boost/hana/experimental/printable.hpp&gt;hana::experimental::print。这是一个实验性(因此不稳定)功能,但我可以向您保证,它最终会以一种或另一种形式进入库:

    #include <boost/hana.hpp>
    #include <boost/hana/experimental/printable.hpp>
    #include <iostream>
    namespace hana = boost::hana;
    
    int main() {
        auto myTuple = hana::tuple_t<int, char*, long>;
        std::cout << hana::experimental::print(myTuple) << std::endl;
    }
    

    输出:

    (type<int>, type<char*>, type<long>)
    

    编辑:一元加号运算符记录在reference of hana::type 中。

    【讨论】:

    • "因此,类型提供了一元 + 运算符的重载,可用于将左值转换为右值。因此,当使用可能是对类型对象的引用的结果时,一个可以使用 + 来确保在获取其嵌套的 ::type 之前获得了一个右值”。谢谢!
    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2021-04-09
    • 1970-01-01
    • 2022-07-28
    相关资源
    最近更新 更多