So I am trying to make a library using boost::hana
that requires the functionality to get the index of a element based on the value:
constexpr auto tup = boost::hana::make_tuple(3_c, boost::hana::type_c<bool>);
auto index = get_index_of_first_matching(tup, boost::hana::type_c<bool>);
// ^^^^^ would be a boost::hana::int_<1>
Is there a possible way to do this? Better yet, is it already in hana
and I don't know about it?
Thanks for the support!
Hana does not provide an algorithm to do this out-of-the-box. If it seems like a much desired feature, I could add such an algorithm fairly easily. It would probably fit well as part of the interface of any
Iterable
, sinceIterable
s are those sequences for which indices are meaningful.For the time being, I would go with something very close to what @cv_and_he proposed in his comment:
A few notes about the above code. First, indices are required to be non-negative in Hana, so it is probably a good idea to use an unsigned type. Secondly, I'm using
hana::drop_while
instead ofhana::take_while
, because the former only requires anIterable
, while the latter requires aSequence
. While it may seem like I'm doing more work (computing the size twice), it turns out that computing the size of most sequences you'll encounter is very fast, so it's not really a concern. Finally, I'm enclosing thehana::size(hana::drop_while(...))
indecltype
, which ensures that no work whatsoever will be done at runtime.How about using
boost::detail::index_if
: