访问tuple_t的类型

Accessing the types of a tuple_t

本文关键字:类型 tuple 访问      更新时间:2023-10-16

我有这个代码:

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类型的方式吗?必须有不那么繁琐的方法。

这确实很棘手。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

另请注意,您可能有兴趣使用 <boost/hana/experimental/printable.hpp> 中的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>)

编辑:一元加运算符记录在hana::type的参考中。