所以我正在尝试使用以下方法创建一个库boost::hana
这需要根据值获取元素索引的功能:
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
我不知道这件事?
感谢您的支持!
Hana 没有提供开箱即用的算法来执行此操作。如果它看起来是一个非常需要的功能,我可以相当容易地添加这样的算法。它可能很适合作为任何界面的一部分Iterable
, since Iterable
s 是索引有意义的序列。
目前,我会采用与 @cv_and_he 在他的评论中提出的非常接近的内容:
#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(...))
in decltype
,这确保在运行时不会完成任何工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)