c++ - 按范围初始化数组

标签 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}; .

有可能吗?

最佳答案

是的,它可以在 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 .

关于c++ - 按范围初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25594551/

相关文章:

c++ - 在 Windows Mobile 中直接访问调制解调器

c++ - vscode 中没有 c_cpp_properties.json 文件

c++ - 如何为指针实现<<和>>?

c - 如何在给定的数组中按顺序插入元素?

javascript - 为什么 compareFunction 必须考虑负值?

C++:如何在模板类中部分特化模板函数

c++ - 如何在不使用继承的情况下将模板实例化为 'rename'?

c++ - 循环永无止境??~需要帮助。 C++

c++ - 数组、函数和随机数

c++ - 模板的合格和不合格名称查找的不同行为