简体   繁体   English

用递增的数字初始化一个编译时常量大小的数组

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

I have an array whose size is set using a compile-time constant (a pre-processor #define in my case). 我有一个数组,其大小是使用编译时常量(在我的情况下为预处理器#define )设置的。 I need to initialize it using consecutive numbers at compile-time. 我需要在编译时使用连续的数字对其进行初始化。 How can I do this? 我怎样才能做到这一点?

Simplified example: 简化示例:

#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

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 ++ 11,但不能使用较新的语言(尽管即使我不能在项目中使用它们,我也有兴趣学习较新的技术)

C++14 code (because of std::integer_sequence ): 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 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. std::integer_sequence等可在C ++ 11中实现,但是如注释中所述,因此将标准版本替换为自制的版本将提供C ++ 11特定的解决方案。

Since boost was mentioned in the comment section, here's another totally different solution based on Boost.PP. 由于注释部分提到了boost,因此这是另一个基于Boost.PP的完全不同的解决方案。 It's also entirely C++03. 它也是完全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 will expand to INIT(z, 0, ?) ... INIT(z, 4, ?) . BOOST_PP_REPEAT将扩展为INIT(z, 0, ?) ... INIT(z, 4, ?) The z is not relevant to our goal, and the ? z与我们的目标无关,而? token is just a placeholder. 令牌只是一个占位符。 Since INIT in turn expands to C(n) for n from 0 to 4 (comma delimited), we get an initializer for a regular C style array. 由于INIT依次将n从0扩展到C(n)到4(以逗号分隔),因此我们得到了常规C样式数组的初始化器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM