我有一个c样式的数组,其大小由a定义,#define并且可以根据编译选项进行更改,例如
#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };
Run Code Online (Sandbox Code Playgroud)
如何将整个数组初始化为非零值,例如all 42?
我不知道C样式数组的解决方案,尽管使用constexpr和C ++ 17可以使用std::array。
constexpr std::array<int, SIZE> createFilledArray (int value){
std::array<int, SIZE> a{0};
for (auto i = 0; i < SIZE; ++i)
a[i] = value;
return a;
}
static constexpr auto myArr = createFilledArray(42);
Run Code Online (Sandbox Code Playgroud)
这样做的缺点是您不能更改数组。如果constexpr从变量中删除,则编译器应该能够对此进行优化。
从C ++ 20开始,您可以强制初始化:
static constinit auto myArr = createFilledArray(42);
Run Code Online (Sandbox Code Playgroud)
不确定投标是否已经合并:请参见constinit投标
| 归档时间: |
|
| 查看次数: |
341 次 |
| 最近记录: |