编译时生成一个省略的整数序列 [英] Compile-time generate integer sequence with one left out
问题描述
回答这里和这里几乎是我需要的。然而,我想能够生成如下的序列:
Answers here and here are pretty much what I need. However, I would like to be able to generate sequences such as:
gen_seq<5, 2> // {0, 1, 3, 4}
gen_seq<3, 0> // {1, 2}
// optional behavior that would be useful for me:
gen_seq<4, 4> // {0, 1, 2, 3}
在示例中,我使用gen_seq生成序列从0到N-1而不是I.这不是强制性的,我也将很好与gen_seq其中N是序列的长度和我缺少的索引或其他变体。
In the examples I used gen_seq to generate a sequence from 0 to N-1 without I. This is not mandatory, I would also be fine with gen_seq where N is the length of the sequence and I the missing index or other variants.
我认为大部分的问题已经在链接的问题中回答。然而,我不能真正包装我的头如何合并第二个参数的离开这一个条件。
I think most of the problem is already answered in the linked questions. However I cannot really wrap my head around how to incorporate the "leave this one out" condition for the second parameter.
理想情况下,我想坚持c ++ 11特性和避免c ++ 14。
Ideally, I would love to stick to c++11 features and avoid c++14. Elegant and especially readable soulutions using c++14 could also be very interesting, though.
推荐答案
您可以使用以下命令:
#if 1 // Not in C++11 // make_index_sequence
#include <cstdint>
template <std::size_t...> struct index_sequence {};
template <std::size_t N, std::size_t... Is>
struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...> {};
template <std::size_t... Is>
struct make_index_sequence<0u, Is...> : index_sequence<Is...> { using type = index_sequence<Is...>; };
#endif // make_index_sequence
namespace detail
{
template <typename Seq1, std::size_t Offset, typename Seq2> struct concat_seq;
template <std::size_t ... Is1, std::size_t Offset, std::size_t ... Is2>
struct concat_seq<index_sequence<Is1...>, Offset, index_sequence<Is2...>>
{
using type = index_sequence<Is1..., (Offset + Is2)...>;
};
}
template <std::size_t N, std::size_t E>
using gen_seq = typename detail::concat_seq<typename make_index_sequence<E>::type, E + 1, typename make_index_sequence<(N > E) ? (N - E - 1) : 0>::type>::type;
static_assert(std::is_same<index_sequence<0, 1, 3, 4>, gen_seq<5, 2>>::value, "");
static_assert(std::is_same<index_sequence<1, 2>, gen_seq<3, 0>>::value, "");
static_assert(std::is_same<index_sequence<0, 1, 2, 3>, gen_seq<4, 4>>::value, "");
这篇关于编译时生成一个省略的整数序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!