使用通用数据初始化多个C++数组

Initialize multiple C++-Arrays with common data

本文关键字:C++ 数组 初始化 数据      更新时间:2023-10-16

我有几个常量C++数组,我想用不同的数据初始化,但前缀总是相同的。此示例编译:

const int array_1[] = { 1, 2, 3, 5, 5 };
const int array_2[] = { 1, 2, 3, 8, 7, 6 };
// ...

是否可以每次都不指定前缀(1, 2, 3)?这将编译并说明它,但缺点是使用宏:

#define prefix 1, 2, 3
const int array_1[] = { prefix, 5, 5 };
const int array_2[] = { prefix, 8, 7, 6 };

要求:

  • 没有宏。
  • 您可以使用 C++11,如果需要,可以使用 C++14。请指定所需的版本。
  • 允许使用 std::array 而不是 C 样式数组。

C++11:

#include <array>
#include <utility>
template<int... Is> struct seq {};
template<int N, int... Is> struct gen_seq : gen_seq<N-1, N-1, Is...> {};
template<int... Is> struct gen_seq<0, Is...> : seq<Is...> {};
template<class T, int N, class... Rs, int... Is>
constexpr auto append(seq<Is...>, T (&lhs)[N], Rs&&... rhs)
-> std::array<T, N+sizeof...(Rs)>
{
    return {{lhs[Is]..., std::forward<Rs>(rhs)...}};
}
template<class T, int N, class... Rs>
constexpr auto append(T (&lhs)[N], Rs&&... rhs)
-> decltype( append(gen_seq<N>{}, lhs, std::forward<Rs>(rhs)...) )
{
    return append(gen_seq<N>{}, lhs, std::forward<Rs>(rhs)...);
}
constexpr int prefix[] = {1,2,3};
constexpr auto array_1 = append(prefix, 5, 5);
constexpr auto array_2 = append(prefix, 8, 7, 6);
#include <iostream>
int main()
{
    std::cout << "array_1: ";
    for(auto const& e : array_1) std::cout << e << ", ";
    std::cout << "n";
    std::cout << "array_2: ";
    for(auto const& e : array_2) std::cout << e << ", ";
}

至于我,除了使用宏之外,我没有其他想法。例如

    #define COMMON_PART 1, 2, 3
    const int array_1[] = { COMMON_PART, 5, 5 };
    const int array_2[] = { COMMON_PART, 8, 7, 6 };