2016-03-22 32 views
1

我有这样的代码:访问类型一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 *' 类型,但如果我这样做:

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类型的方法吗?一定不那么繁琐。

回答

3

这确实很棘手。 Hana在hana::type上提供了一个加法运算符,它将任何符合资格的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 

另外请注意,你可能有兴趣使用hana::experimental::print<boost/hana/experimental/printable.hpp>。这是一个实验(因此不稳定)功能,但我可以向你保证,它最终应该做它的方式到库中,以某种形式或其他:

#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中记录了一元加运算符。

+0

“出于这个原因,类型提供了一元运算符的重载,可用于将左值转换为右值。因此,当使用可能引用类型对象的结果时,可以使用+确保在获取它的嵌套::类型之前获得一个右值“。谢谢! – chila