用递增的数字初始化一个编译时常量大小的数组 [英] initialize an array of compile-time constant size with incrementing numbers
问题描述
我有一个数组,其大小是使用编译时常量设置的(在我的情况下为预处理器 #define
)。我需要在编译时使用连续的数字对其进行初始化。我该怎么做?
I have an array whose size is set using a compile-time constant (a pre-processor #define
in my case). I need to initialize it using consecutive numbers at compile-time. How can I do this?
简化示例:
#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,但不能使用较新的(尽管即使我不能在项目中使用较新的技术,我也会对此感兴趣。)
I can use C++11, but not newer (although I would be interested to learn of newer techniques even if I can't use them for this project)
推荐答案
C ++ 14个代码(由于 std :: integer_sequence
):
C++14 code (because of 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特定解决方案。
std::integer_sequence
and the like are implementable in C++11 however as noted in a comment, so substituting the standard version for a home-brewed one will give a C++11 specific solution.
这篇关于用递增的数字初始化一个编译时常量大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!