Skip to content

Instantly share code, notes, and snippets.

@goldshtn
Last active August 29, 2015 14:13
Show Gist options
  • Save goldshtn/ea610da529ecb2fc1af5 to your computer and use it in GitHub Desktop.
Save goldshtn/ea610da529ecb2fc1af5 to your computer and use it in GitHub Desktop.
Sort a typelist by size at compile-time, using quicksort.
template <typename Predicate, typename Head, typename... Tail>
struct typelist_sort_t<Predicate, typelist<Head, Tail...>>
{
using predicate = meta_partial_apply<Predicate, Head>;
using notpredicate = meta_negate<predicate>;
using smaller_than = typelist_filter<notpredicate, typelist<Tail...>>;
using greater_than = typelist_filter<predicate, typelist<Tail...>>;
using type = typelist_cat<
typelist_sort<Predicate, smaller_than>,
typelist<Head>,
typelist_sort<Predicate, greater_than>
>;
};
template <typename Predicate, typename Typelist>
using typelist_sort = typename typelist_sort_t<Predicate, Typelist>::type;
struct meta_less_sizeof_t
{
template <typename T1, typename T2>
struct apply
{
static constexpr bool value = sizeof(T1) < sizeof(T2);
using type = metabool<value>;
};
};
template <typename Typelist>
using typelist_sort_by_size = typelist_sort<meta_less_sizeof_t, Typelist>;
// Example use:
static_assert(is_same<
typelist<char, short, int, long long, long double>,
typelist_sort_by_size<typelist<int, short, long double, long long, char>>>::value, "");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment