我有一个数组,其大小是使用编译时常量(#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特定的解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句