提升hana获得第一匹配的索引
Boost hana get index of first matching
因此,我正试图使用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
接口的一部分,因为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(...))
封装在decltype
中,这确保了在运行时不会完成任何工作。
如何使用boost::detail::index_if
:
#include <boost/hana.hpp>
template <typename Haystack, typename Needle>
constexpr auto get_index_of_first_matching(Haystack&&, Needle&& n)
{
using Pred = decltype(boost::hana::equal.to(n));
using Pack = typename boost::hana::detail::make_pack<Haystack>::type;
constexpr auto index = boost::hana::detail::index_if<Pred, Pack>::value;
return boost::hana::int_c<index>;
}
int main()
{
using namespace boost::hana::literals;
constexpr auto tup = boost::hana::make_tuple(3_c, boost::hana::type_c<bool>);
constexpr auto index = get_index_of_first_matching(tup, boost::hana::type_c<bool>);
static_assert(index == boost::hana::int_c<1>, "index is wrong");
return 0;
}
相关文章:
- 使用移位的无符号数字作为数组的索引号是一种很好的做法
- 有没有一种简单的方法可以在C++中获取特定索引之后向量中的所有项目?
- 在 c++ 中将数组的值分配给另一个数组的索引
- C ++将文本存储在数组的不同索引中,并带有一两个
- 使用 C++ GMock 匹配器测试unordered_map的密钥是否来自一组密钥
- 如何在另一个数组中找到一个未排序数组的不同元素索引?
- 有没有一种简单的方法可以忽略 c++ 中的索引错误
- 如何在编译时从两个索引序列创建一个数组
- 使用Boost.Preprocessor生成类模板的一组标记和索引的专门化
- 将一维数组的索引转换为二维数组
- 设置数组一次索引很多?复合文字
- 需要一种在平面表示中进行数组索引的算法
- 构造一个数组的有效方法,该数组采用C++中另一个数组中具有给定索引的元素
- 在一个数组中查找最高分数,并将该索引与另一个数组的索引匹配
- 使用double-for循环索引一维数组
- array:将一维数组的索引转换为多维数组的向量索引
- 嵌套循环 - 一维索引
- 填充 c++ 数组时遇到问题,每个索引处只有最后一项
- 将一维"flattened"索引转换为 N 维数组的 N 维向量索引
- C++:有没有一种有效的方法来语法上使用指针等索引