初始化具有递增数字的编译时常量大小的数组

initialize an array of compile-time constant size with incrementing numbers

本文关键字:常量 数组 编译 初始化 数字      更新时间:2023-10-16

我有一个数组,其大小是使用编译时常量(在我的例子中是预处理器#define)设置的。我需要在编译时使用连续的数字初始化它。我该怎么做?

简化示例:

#define ARR_SZ 5
struct C {
  C(int a) : a(a) {}
  int a;
};
C arr[ARR_SZ] = {{0},{1},{2},{3},{4}}; // This needs to adapt to any number

我可以使用C++11,但不能更新(尽管即使我不能将它们用于这个项目,我也有兴趣学习更新的技术)

C++14 代码(因为std::integer_sequence):

#include <type_traits>
#include <array>
#define ARR_SZ 5
struct C {
  C(int a) : a(a) {}
  int a;
};
template<int ...Is>
auto make_C_arr(std::integer_sequence<int, Is...>) -> std::array<C, sizeof...(Is)> {
    return {{ {Is}... }};
}
auto arr = make_C_arr(std::make_integer_sequence<int, ARR_SZ>{});
int main () {
}

std::integer_sequence等可以在 C++11 中实现,但如评论中所述,因此将标准版本替换为自制版本将给出 C++11 的特定解决方案。

由于评论部分提到了boost,这里有另一个基于Boost.PP的完全不同的解决方案。它也完全是C++03。

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#define ARR_SZ 5
struct C {
  C(int a) : a(a) {}
  int a;
};
#define INIT(z, n, d) BOOST_PP_COMMA_IF(n) C(n)
C arr[ARR_SZ] = { BOOST_PP_REPEAT(ARR_SZ, INIT, ?) };

int main () {
}

BOOST_PP_REPEAT将扩展到INIT(z, 0, ?) ... INIT(z, 4, ?)z与我们的目标无关,?令牌只是一个占位符。由于 INIT 依次从 0 扩展到 4(逗号分隔)的n C(n),因此我们得到了常规 C 样式数组的初始值设定项。