繁体   English   中英

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

[英]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依次将n从0扩展到C(n)到4(以逗号分隔),因此我们得到了常规C样式数组的初始化器。

暂无
暂无

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

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