【发布时间】: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<1ul, 3ul>。
【问题讨论】:
-
你的代码有什么问题?无论如何,它只会被藏在图书馆的标题中,所以谁在乎它是否有点令人费解。我对如何以不同的方式做到这一点有一些想法,但在不知道您当前方法的问题是什么的情况下,很难弄清楚什么是最好的。
-
我的代码没有问题。我发布它是为了解释我想要做什么。我只是想知道 Hana 有没有这方面的算法。
标签: c++ tuples c++14 boost-hana