使用通用数据初始化多个C++数组
Initialize multiple C++-Arrays with common data
我有几个常量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 };
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '