Peter Dimov writes:
Louis Dionne wrote:
Eric Niebler writes:
...
FWIW, these indices don't seem all that useful to me. What exactly was
the desired behavior?
No idea
The desired behavior was for indexing the sorted tuple to work like indexing
the original tuple. That is, given tuple, you were supposed to produce another tuple for which get<0> still
returns char[4], even though the first element is physically char[1].
Oh, yes of course. Then I think the original code did not do the
right thing, or I made a mistake while translating it to Hana.
Anyway, here's a version that does what was probably needed by
the OP (notice the additional indexed_sort of the indices):
------------------------------------------------------------------------------
#include
#include
#include
#include
#include
#include
using namespace boost::hana;
using namespace boost::hana::literals;
auto indexed_sort = [](auto list, auto predicate) {
auto indexed_list = zip(list, to<Tuple>(range(0_c, size(list))));
auto sorted = sort_by(predicate ^on^ head, indexed_list);
return make_pair(transform(sorted, head), transform(sorted, last));
};
int main() {
auto types = tuple_t;
auto sorted = indexed_sort(types, [](auto t, auto u) {
return sizeof_(t) < sizeof_(u);
});
using Tup = decltype(unpack(first(sorted), template_<_tuple>))::type;
auto indices = second(indexed_sort(second(sorted), less));
// When accessed through the indices sequence, the tuple appears to be
// ordered as the `types` above. However, as can be seen in the
// static_assert below, the tupleĀ is actually ordered differently.
Tup tup;
char(&a)[4] = tup[indices[0_c]];
char(&b)[2] = tup[indices[1_c]];
char(&c)[1] = tup[indices[2_c]];
char(&d)[5] = tup[indices[3_c]];
char(&e)[3] = tup[indices[4_c]];
static_assert(std::is_same<
Tup,
_tuple
>{}, "");
}
------------------------------------------------------------------------------
It should also be noted that Hana does not guarantee any particular
layout for tuples. Hence, having
_tuple
does not mean that it's akin to a struct defined as
struct {
char member1[1];
char member2[2];
char member3[3];
char member4[4];
char member5[5];
};
Instead, if one requires a special layout, a new structure which
ensures the right physical layout should be created. At the same
time, this structure could take care of the indexing business to
abstract it from the user. This can be done easily by using Hana's
extension mechanism.
Regards,
Louis