代码之家  ›  专栏  ›  技术社区  ›  Baruch

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

  •  1
  • Baruch  · 技术社区  · 6 年前

    我有一个数组,其大小是使用编译时常量(预处理器)设置的 #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,但不是更新的(虽然我会感兴趣的新技术,即使我不能使用他们为这个项目)

    2 回复  |  直到 6 年前
        1
  •  3
  •   StoryTeller - Unslander Monica    6 年前

    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 () {
    
    }
    

    标准::整数序列 类似的是在C++ 11中实现的,但是正如注释中所提到的,因此用标准版本代替自制的版本将给出一个C++ 11的具体解决方案。

        2
  •  0
  •   StoryTeller - Unslander Monica    6 年前

    因为在注释部分提到了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 依次扩展到 C(n) 对于 n 从0到4(逗号分隔),我们得到了常规C样式数组的初始值设定项。