Search code examples
c++boostboost-hana

Accessing the types of a tuple_t


I have this code:

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

This outputs:

boost::hana::type_impl<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;

It outputs:

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;

Then it outputs 'char*'.

Is this the way to access the types of a tuple_t? There must be less cumbersome way.


Solution

  • 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
    

    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;
    }
    

    Output:

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

    Edit: The unary plus operator is documented in the reference of hana::type.