在定义 C 风格数组或 C++11 数组时,通常需要获取编译时常量来表示此类数组的大小。在 C 中,宏用于执行此类操作而不依赖可变长度数组(因为它在 C99 中不是标准的):
#define ARRAY_SIZE 1024
int some_array[ARRAY_SIZE];
或
#define countof(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0]))
在 C++ 中,是否可以定义更惯用的东西?
最佳答案
使用 C++ 的 constexpr
,可以找到数组的编译时常量大小:
template<std::size_t N, class T>
constexpr std::size_t countof(T(&)[N]) { return N; }
并按如下方式使用它:
int some_array[1024];
static_assert(countof(some_array) == 1024, "wrong size");
struct {} another_array[1];
static_assert(countof(another_array) == 1, "wrong size");
参见 full program demo on coliru .
如果喜欢交替使用 std::array
和 C 风格的数组,可以使用 SFINAE 添加 countof
的定义 >std::array
s 和 std::tuple
s:
template<class Array, std::size_t N = std::tuple_size<Array>::value>
constexpr std::size_t countof(Array&) { return N; }
关于c++ - 如何在编译时获取数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49454005/