我有几个 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 };
要求:
- 没有宏。
- 您可以使用 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 << ", ";
}
关于c++ - 使用公共(public)数据初始化多个 C++ 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821067/