A sequence of indices of elements of a tuple satisfying a predicate in Hahn
Is there a concise way to get a sequence of indices of elements of a tuple that satisfy a predicate in Hana ?
Here is the code I wrote to do this using only the standard library:
template <template<typename> typename Pred, typename Tuple>
class get_indices_of {
static constexpr size_t size = std::tuple_size<Tuple>::value;
template <size_t I, size_t... II> struct impl {
using type = std::conditional_t<
Pred<std::tuple_element_t<I,Tuple>>::value,
typename impl<I+1, II..., I>::type,
typename impl<I+1, II...>::type >;
};
template <size_t... II> struct impl<size,II...> {
using type = std::index_sequence<II...>;
};
public:
using type = typename impl<0>::type;
};
template <template<typename> typename Pred, typename Tuple>
using get_indices_of_t = typename get_indices_of<Pred,Tuple>::type;
Usage example:
using types = std::tuple<std::string,int,double,char>;
using ints = get_indices_of_t<std::is_integral,types>;
Type ints
now std::index_sequence<1ul, 3ul>
.
+3
source to share
1 answer
I would suggest something like this:
constexpr auto get_indices_of = [](auto tuple, auto predicate){
constexpr auto indices = to<tuple_tag>(range_c<std::size_t, 0, size(tuple)>);
return filter(indices, [=](auto i){ return predicate(tuple[i]); });
};
The only inconvenient part is getting the indexes as range_c
it is not itself MonadPlus. Your actual example using this function:
constexpr auto types = make_tuple(
type_c<std::string>, type_c<int>, type_c<double>, type_c<char>);
constexpr auto ints = get_indices_of(types, trait<std::is_integral>);
+2
source to share