定义 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");
请参阅 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 上的丰富的程序演示。
如果你不想引入自己的函数而只能使用STL来实现,那么可以使用
std::distance
来检索大小:
#include <utility>
auto size = std::distance(std::begin(some_array), std::end(some_array));
从 C++17 开始
constexpr
不太直观,但在 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