用递增的数字初始化一个编译时常量大小的数组 [英] initialize an array of compile-time constant size with incrementing numbers

查看:108
本文介绍了用递增的数字初始化一个编译时常量大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其大小是使用编译时常量设置的(在我的情况下为预处理器 #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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆