如何在编译时获取数组大小? [英] How to get an array size at compile time?
问题描述
在定义C型数组或C ++ 11数组时,通常需要获取一个编译时常量来表示此类数组的大小。在C语言中,宏用于执行此类操作而不依赖于可变长度数组(因为在C99中不是标准的):
When defining either a C-style array or a C++11 array, one often need to get a compile-time constant to express the size of such array. In C, a macro is used to do such a thing without relying on variable-length array (as it wasn't standard in C99):
#define ARRAY_SIZE 1024
int some_array[ARRAY_SIZE];
或
#define countof(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0]))
在C ++中,可以定义一些更惯用的东西吗?
In C++, is it possible to define something more idiomatic?
推荐答案
如果您的标准库是C ++ 17兼容,只需使用 std :: size(xyz)
。
If your standard-library is C++17-compatible, just use std::size(xyz)
.
如果您的标准库尚未提供此功能,则很容易实现自己, constexpr
-说明符为C ++ 11 。
If your standard-library doesn't already provide that, it's easy to implement yourself, the constexpr
-specifier is C++11.
这篇关于如何在编译时获取数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!