我有几个const 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 };
要求:
std::array
而不是C风格的数组。答案 0 :(得分:4)
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 << ", ";
}
答案 1 :(得分:0)
至于我,除了使用宏之外别无其他想法。例如
#define COMMON_PART 1, 2, 3
const int array_1[] = { COMMON_PART, 5, 5 };
const int array_2[] = { COMMON_PART, 8, 7, 6 };