Skip to content

Instantly share code, notes, and snippets.

@ricejasonf
Last active March 2, 2016 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricejasonf/8c2b54c182e6038fd0ce to your computer and use it in GitHub Desktop.
Save ricejasonf/8c2b54c182e6038fd0ce to your computer and use it in GitHub Desktop.
Filter Index Sequence
#include<boost/hana/filter.hpp>
#include<utility>
#include "hpesoj_utility.hpp"
namespace hana = boost::hana;
struct is_even_t {
template <int i>
struct apply {
static constexpr bool value = i % 2 == 0;
};
};
constexpr is_even_t is_even{};
template <std::size_t ...x, typename Indices, std::size_t ...i>
constexpr auto filter_helper(std::index_sequence<x...> const&, Indices const&, std::index_sequence<i...> const&) {
constexpr std::size_t values[] = {x...};
return std::index_sequence<values[Indices::indices[i]]...>{};
}
template <std::size_t ...x, typename Pred>
constexpr auto filter(std::index_sequence<x...> const& values, Pred const&) {
using Indices = hana::detail::filter_indices<Pred::template apply<x>::value...>;
return filter_helper(values, Indices{}, std::make_index_sequence<Indices::indices.size()>{});
}
int main() {
constexpr auto xs = hpesoj::make_index_sequence_t<10000>{};
constexpr auto evens = filter(xs, is_even);
}
#include <utility>
namespace hpesoj {
template<typename S1, typename S2>
struct build_index_sequence;
template<typename S1, typename S2>
using build_index_sequence_t = typename build_index_sequence<S1, S2>::type;
template<
std::size_t... Cs1,
std::size_t... Cs2
>
struct build_index_sequence<
std::index_sequence<Cs1...>,
std::index_sequence<Cs2...>
>
{
using type = std::index_sequence<Cs1..., sizeof...(Cs1) + Cs2...>;
};
template<std::size_t N>
struct make_index_sequence;
template<std::size_t N>
using make_index_sequence_t =
typename make_index_sequence<N>::type;
template<std::size_t N>
struct make_index_sequence
{
using type = build_index_sequence_t<
make_index_sequence_t<N / 2>,
make_index_sequence_t<N - N / 2>
>;
};
template<>
struct make_index_sequence<1>
{
using type = std::index_sequence<0>;
};
template<>
struct make_index_sequence<0>
{
using type = std::index_sequence<>;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment