【问题标题】:Sequence of indices of tuple elements satifying predicate in HanaHana中满足谓词的元组元素的索引序列
【发布时间】:2017-07-05 20:05:50
【问题描述】:

是否有一种简洁的方法来获取满足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&lt;1ul, 3ul&gt;

【问题讨论】:

  • 你的代码有什么问题?无论如何,它只会被藏在图书馆的标题中,所以谁在乎它是否有点令人费解。我对如何以不同的方式做到这一点有一些想法,但在不知道您当前方法的问题是什么的情况下,很难弄清楚什么是最好的。
  • 我的代码没有问题。我发布它是为了解释我想要做什么。我只是想知道 Hana 有没有这方面的算法。

标签: c++ tuples c++14 boost-hana


【解决方案1】:

我猜是这样的:

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

【讨论】:

  • 猫狗互相回答元编程问题 - 集体歇斯底里!顺便说一句,还有一个对此功能的开放请求github.com/boostorg/hana/issues/273
  • 从技术上讲,您需要to&lt;tuple_tag&gt;(range_c&lt;...&gt;) 的原因是因为range_c 不是MonadPlus(请参阅this),而不是因为它不是Sequence。这只是一个挑剔,否则你的答案是正确的。
  • @LouisDionne 一定是在使用旧的 hana,我发誓静态断言说它必须是一个序列 - 绝对是 MonadPlus。哎呀。
猜你喜欢
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多