按范围初始化数组

时间:2014-08-31 17:36:41

标签: c++ arrays templates initialization range

我需要创建一个包含范围内所有值的数组。创建后我无法设置值,因为数组必须是constexpr。

template<int FIRST, int LAST>
struct Foo
{
    static constexpr int array[LAST - FIRST + 1] = ???;
};

例如Foo<3, 7>::array;

应相当于static constexpr int array[5] = {3, 4, 5, 6, 7};

甚至可能吗?

2 个答案:

答案 0 :(得分:4)

是的,它可以在C ++ 11中完成。不,它不漂亮。您基本上需要重新实现C ++ 14的编译时整数序列。

///////////////// Reimplement compile-time integer sequences ///////////////////////
// There's plenty of better implementations around.
// This one is similar to libstdc++'s implementation.
template<class T, T... Ints>
struct integer_seq {
    using next = integer_seq<T, Ints..., sizeof...(Ints)>;
    static constexpr std::size_t size() { return sizeof...(Ints); }
};

template<class T, int Len>
struct seq_builder{
    static_assert(Len > 0, "Length must be nonnegative");
    using type = typename seq_builder<T, Len-1>::type::next;
};

template<class T>
struct seq_builder<T, 0>{
    using type = integer_seq<T>;
};

template<class T, int length>
using make_int_sequence = typename seq_builder<T, length>::type;

/////////////////// Actual stuff starts here/////////////////////////////////

template<int FIRST, int LAST, class = make_int_sequence<int, LAST+1-FIRST>>
struct Foo;

template<int FIRST, int LAST, int... SEQ>
struct Foo<FIRST, LAST, integer_seq<int, SEQ...>>
{
    static constexpr int array[sizeof...(SEQ)] = {(FIRST+SEQ)...};
};

template<int FIRST, int LAST, int... SEQ>
constexpr int Foo<FIRST, LAST, integer_seq<int, SEQ...>>::array[sizeof...(SEQ)];

Demo

答案 1 :(得分:0)

在提议的C++14标准中是可能的。我认为C ++ 11不可能。

如果你真的必须这样做,并且不只是有一些你可以硬编码的数组,你可以求助于C宏。显然有些库help you perform loops in macros