2016-03-22 35 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