问题描述
所以我正在尝试使用boost::hana
创建一个库,该库需要具有基于值来获取元素索引的功能:
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>
有没有办法做到这一点?更好的是,它已经在hana
中并且我不知道吗?
Is there a possible way to do this? Better yet, is it already in hana
and I don't know about it?
感谢支持!
推荐答案
Hana不提供开箱即用的算法.如果它似乎是非常需要的功能,则可以相当轻松地添加这样的算法.它可能很适合作为任何Iterable
接口的一部分,因为Iterable
是那些对索引有意义的序列.
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
, since Iterable
s are those sequences for which indices are meaningful.
就目前而言,我会采用非常类似于@cv_and_he在他的评论中提出的建议:
For the time being, I would go with something very close to what @cv_and_he proposed in his comment:
#include <boost/hana.hpp>
namespace hana = boost::hana;
template <typename Iterable, typename T>
constexpr auto index_of(Iterable const& iterable, T const& element) {
auto size = decltype(hana::size(iterable)){};
auto dropped = decltype(hana::size(
hana::drop_while(iterable, hana::not_equal.to(element))
)){};
return size - dropped;
}
constexpr auto tuple = hana::make_tuple(hana::int_c<3>, hana::type_c<bool>);
constexpr auto index = index_of(tuple, hana::type_c<bool>);
static_assert(index == hana::size_c<1>, "");
int main() { }
有关上述代码的一些注意事项.首先,在Hana中要求索引必须为非负数,因此使用无符号类型可能是一个好主意.其次,我使用的是hana::drop_while
而不是hana::take_while
,因为前者只需要一个Iterable
,而后者则需要一个Sequence
.虽然看起来我在做更多的工作(两次计算大小),但事实证明,计算您将遇到的大多数序列的大小非常快,因此这并不是真正的问题.最后,我将hana::size(hana::drop_while(...))
括在decltype
中,以确保在运行时不会进行任何工作.
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 of hana::take_while
, because the former only requires an Iterable
, while the latter requires a Sequence
. 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 the hana::size(hana::drop_while(...))
in decltype
, which ensures that no work whatsoever will be done at runtime.
这篇关于Boost Hana获取第一个匹配项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!