Search code examples
c++boost-hana

How to tranform a hana::tuple_t with an arbitrary type meta-function?


Lets say I have two types each having an internal type:

struct A1{
    using type = int;
};
struct B1{
    using type = double;
};

I created a hana::tuple_t from my classes (e.g. auto Types = hana::tuple_t<A1, B1>) and I would like to get a similar hana::tuple_t of the internal types of my class (e.g. hana::tuple_t<A1::type, B1::type>)

I wanted to use the transform function to get the resulting tuple_t:

auto result = hana::transform(Types, [](auto t){return t::type;});

I get the compile error :

error: ‘t’ is not a class, namespace, or enumeration

What is the correct way to achieve this using hana::tranform?


Solution

  • You can use hana::template_

    template<typename O>
    using inner_type = typename O::type;
    auto result = hana::transform(Types, hana::template_<inner_type>);
    

    tuple_t produces a tuple, which cannot contain types. Instead it contains hana::types, which are values that represent types. template_ turns a type-level function (a template type alias or class) into a value-level "metafunction". If you want to use an explicit lambda for the transform, you can, but it gets gory:

    auto result = hana::transform(Types, [](auto t) { return hana::type_c<typename decltype(t)::type::type>; })
    

    The type of t in the lambda is hana::type<T> for some T, so decltype(t) unwraps that type from the value, the first ::type gets T, the second ::type gets your target type, and the type_c wraps it all back up.