初始化具有递增数字的编译时常量大小的数组
initialize an array of compile-time constant size with incrementing numbers
我有一个数组,其大小是使用编译时常量(在我的例子中是预处理器#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 样式数组的初始值设定项。
相关文章:
- C++常量数组的编译时间较长
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 使用双指针传递 2D 常量数组
- 检查输入 std::array 指针数据是否等于某个常量数组
- 如何在可执行文件中存储常量数组?
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- LLVM 无法将数组类型强制转换为常量数组
- 如何在C++中的单行中返回常量数组中的值
- C++ 具有常量数组和initializer_list的重载构造函数
- 在可变参数构造函数中初始化常量数组
- 非常量数组
- C/C++ 中的常量数组和静态常量数组有什么区别
- C++全局常量数组:是否保证合并(优化)到一个副本中
- 在常量数组上使用指针遍历
- 具有函数指针常量数组的 C++ 模板化静态类
- 字符常量数组为空,即使已为其赋值 [C++]
- 指向常量数组的指针
- 函数指针的常量数组令人困惑
- 在 c++ 中初始化静态常量数组
- 常量数组类成员初始化