访问tuple_t的类型 [英] Accessing the types of a tuple_t
问题描述
我有此代码:
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 *'类型,但是如果我这样做:
I want to access the 'char*' type, but if I do:
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
这是因为它是参考,如果我这样做:
It's because it is a reference, if I do:
std::cout << boost::typeindex::type_id<decltype(boost::hana::traits::remove_reference(myTuple[1_c]))::type>().pretty_name() << std::endl;
然后它输出'char *'.
Then it outputs 'char*'.
这是访问tuple_t类型的方法吗?一定没有那么麻烦的方法.
Is this the way to access the types of a tuple_t? There must be less cumbersome way.
推荐答案
这确实很棘手. Hana在hana::type
上提供了一元加号运算符,该运算符会将所有经过ref限定的hana::type
衰减为右值.所以基本上,
This is indeed tricky. Hana provides a unary plus operator on hana::type
that decays any ref-qualified hana::type
to a rvalue. So basically,
#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
感兴趣.这是一项实验性功能(因此不稳定),但是我可以向您保证,它最终应以一种或另一种形式进入库中:
Also note that you might be interested in using hana::experimental::print
from <boost/hana/experimental/printable.hpp>
. This is an experimental (hence unstable) feature, but I can assure you it should eventually make its way into the library, in one form or the other:
#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
.
Edit: The unary plus operator is documented in the reference of hana::type
.
这篇关于访问tuple_t的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!