Search code examples
c++boost-hana

How to retrieve types from boost::hana::tuple_t?


I have using hana:tuple_t to store and retrieve a typelist:

auto Types = hana::tuple_t<int, double>;
auto first_t = Types[hana::int_c<0>];
static_assert(std::is_same_v<decltype(first_t)::type, int>); // line 3

The above code, works correctly, however when I tried to replace the variable first_t by its actual expression:

static_assert(std::is_same_v<decltype(Types[hana::int_c<0>])::type, int>); //line 4

I get a compile error:

template argument 1 is invalid
     static_assert(std::is_same_v<decltype(Types[hana::int_c<0>])::type, int>);
 error: decltype evaluates to ‘const boost::hana::type_impl<int>::_&’, which is not a class or enumeration type

Line 3 and Line 4 of the above code are equivalent, how come I get the compile error for line 4:


Solution

  • decltype(Types[hana::int_c<0>]) is a const reference to boost::hana::type_impl<int>::_ and you cannot query a reference to get the ::type from the referenced type.

    first_t is declared with just auto, and that removes the reference and the constness. If you wanted to keep that (in a different situation), you could declare it auto & first_t = ....

    static_assert(std::is_same_v<decltype(first_t), boost::hana::type_impl<int>::_>);
    

    You can use std::decay_t to get rid of the reference.

    static_assert(std::is_same_v<
        std::decay_t<decltype(Types[hana::int_c<0>])>::type, int>);