如何在编译时获取数组大小?

问题描述 投票:0回答:4

定义 C 样式数组或 C++11 数组时,通常需要获取一个编译时常量来表示此类数组的大小。在 C 中,宏用于执行此类操作,而不依赖于可变长度数组(因为它在 C99 中不是标准的):

#define ARRAY_SIZE 1024
int some_array[ARRAY_SIZE];

#define countof(ARRAY) (sizeof(ARRAY)/sizeof(ARRAY[0]))

在C++中,是否可以定义更惯用的东西?

c++ arrays c++11
4个回答
13
投票

使用 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");

请参阅 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; }

查看 coliru 上的丰富的程序演示


12
投票

如果您的标准库与 C++17 兼容,只需使用

std::size(xyz)

如果您的标准库尚未提供该功能,您自己也可以轻松实现,

constexpr
说明符是 C++11


1
投票

如果你不想引入自己的函数而只能使用STL来实现,那么可以使用

std::distance
来检索大小:

#include <utility>
auto size = std::distance(std::begin(some_array), std::end(some_array));

从 C++17 开始

constexpr


0
投票

不太直观,但在 C++17 中

std::tuple_size_v<std::array<T,N>>
正是我所寻找的。

或者在 C++11 中:

std::tuple_size<std::array<T,N>>::value

https://en.cppreference.com/w/cpp/container/array/tuple_size

© www.soinside.com 2019 - 2024. All rights reserved.