Boost logo

Boost :

Subject: Re: [boost] [TypeSort] Automatic type sorting
From: Louis Dionne (ldionne.2_at_[hidden])
Date: 2015-03-20 14:44:37


Mathias Gaunard <mathias.gaunard <at> ens-lyon.org> writes:

>
> [...]
>
> You probably need to be able to access the final tuple with the original
> indices though, which is a bit more involved.
>
> [...code...]
>
> This could make an interesting addition to Boost.Fusion.

As a simple curiosity, here's how this could be implemented with Hana:

------------------------------------------------------------------------------
#include <boost/hana/functional.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/range.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>

#include <iostream>
namespace hana = boost::hana;
using namespace hana::literals;

int main() {
    auto types = hana::tuple_t<short, int, short>;
    auto indexed_types = hana::zip(
        types, hana::to<hana::Tuple>(hana::range(0_c, hana::size(types)))
    );

    auto sorted_indexed_types = hana::sort_by([](auto t, auto u) {
        return hana::sizeof_(t[0_c]) < hana::sizeof_(u[0_c]);
    }, indexed_types);

    auto sorted_types = hana::transform(sorted_indexed_types, hana::head);
    auto sorted_indices = hana::transform(sorted_indexed_types, hana::last);
    using tuple = decltype(
        hana::unpack(sorted_types, hana::template_<hana::_tuple>)
    )::type;

    tuple t;
    std::cout << sizeof(t[sorted_indices[0_c]]) << std::endl;
    std::cout << sizeof(t[sorted_indices[1_c]]) << std::endl;
    std::cout << sizeof(t[sorted_indices[2_c]]) << std::endl;
}
------------------------------------------------------------------------------

It's essentially the same thing than with MPL/Fusion, except there's a bit
more syntactic sugar because of C++14 features. Also, this example showcases
how low the syntactic cost of the MPL/Fusion unification is. The only place
where we need to bridge between types and values is

    using tuple = decltype(
        hana::unpack(sorted_types, hana::template_<hana::_tuple>)
    )::type;

which is (IMO) not too cumbersome.

Regards,
Louis

P.S.: I know the order of the arguments to sort_by is backwards. I'm working
      on a consistent scheme for these algorithms.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk