gpt4 book ai didi

c++ - Hana 中满足谓词的元组元素索引序列

转载 作者:太空狗 更新时间:2023-10-29 21:34:53 34 4
gpt4 key购买 nike

是否有一种简洁的方法来获取满足Hana中的谓词的元组元素的索引序列? ?

这是我只使用标准库为此编写的代码:

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;

使用示例:

using types = std::tuple<std::string,int,double,char>;
using ints = get_indices_of_t<std::is_integral,types>;

ints 的类型现在是std::index_sequence<1ul, 3ul> .

最佳答案

我猜是这样的:

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]); });
};

唯一尴尬的部分是获取索引,因为 range_c 本身不是 MonadPlus。您使用此函数的实际示例是:

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>);

关于c++ - Hana 中满足谓词的元组元素索引序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935075/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com