正在初始化大小为(int)的常量数组
Initializing a const array with size sizeof(int)
如果我想在c++中初始化一个大小为(int)的常量整数数组,我该怎么做?例如,我可能想要一个数组,它的大小为(int)*8 int,第n位为(array[n]=1<<n)。
我不认为在不指定每个元素的情况下初始化静态大小的const
对象数组,至少在它不是类的成员时不能。但是,您可以初始化对静态大小的const
对象数组的引用:
template <int N>
struct foo
{
static bool init(int* array) {
unsigned int bit(1);
for (int i(0); i != N; ++i) {
array[i] = bit << i;
}
return true;
}
static void use(bool) {}
static int const (&array())[N] {
static int rc[N];
static bool dummy(init(rc));
use(dummy);
return rc;
}
};
int const (&array)[sizeof(int) * 8] = foo<sizeof(int) * 8>::array();
如果您真的想初始化一个静态大小的数组,可以使用可变模板来初始化,但数组需要是类类型的静态成员。由于代码不太明显,所以它是:
template <int...> struct indices {};
template <int N, typename> struct make_list;
template <int... Indices>
struct make_list<0, indices<Indices...>> {
typedef indices<0, Indices...> type;
};
template <int N, int... Indices>
struct make_list<N, indices<Indices...>> {
typedef typename make_list<N-1, indices<N, Indices...>>::type type;
};
template <int N, typename> struct array_aux;
template <int N, int... Indices>
struct array_aux<N, indices<Indices...>>
{
static int const values[N];
};
template <int N, int... Indices>
int const array_aux<N, indices<Indices...>>::values[N] = { 1u << Indices... };
template <int N = sizeof(int) * 8>
struct array
: array_aux<N, typename make_list<N-1, indices<>>::type>
{
};
有了这个,你就可以使用这样的东西访问阵列:
array<>::values[i]
这里有一种初始化4个整数的常量数组的方法,其中sizeof(int)==4:
#define SHIFT(__n) (1 << __n++)
int main()
{
int n = 0;
const int ir4[sizeof(int)] = {SHIFT(n), SHIFT(n), SHIFT(n), SHIFT(n)};
...
}
您可以使用std::array和模板
template<typename T, std::size_t N>
std::array<T, sizeof(T)*N> array_init() {
std::array<T, sizeof(T)*N> ints;
for (T n = 0; n < sizeof(T)*N; ++n) {
ints[n] = 1 << n;
}
return ints;
}
然后你把它叫做
auto ints = array_init<int, 8>();
相关文章:
- C++常量数组的编译时间较长
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 使用双指针传递 2D 常量数组
- 检查输入 std::array 指针数据是否等于某个常量数组
- 如何在可执行文件中存储常量数组?
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- LLVM 无法将数组类型强制转换为常量数组
- 如何在C++中的单行中返回常量数组中的值
- C++ 具有常量数组和initializer_list的重载构造函数
- 在可变参数构造函数中初始化常量数组
- 非常量数组
- C/C++ 中的常量数组和静态常量数组有什么区别
- C++全局常量数组:是否保证合并(优化)到一个副本中
- 在常量数组上使用指针遍历
- 具有函数指针常量数组的 C++ 模板化静态类
- 字符常量数组为空,即使已为其赋值 [C++]
- 指向常量数组的指针
- 函数指针的常量数组令人困惑
- 在 c++ 中初始化静态常量数组
- 常量数组类成员初始化