数组大小类型在编译时是安全的
#include <stddef.h> // size_t, ptrdiff_t
//----------------------------------- Machinery:
using Size = ptrdiff_t;
template< class Item, size_t n >
constexpr auto n_items( Item (&)[n] ) noexcept
-> Size
{ return n; }
//----------------------------------- Usage:
#include <iostream>
using namespace std;
auto main()
-> int
{
int const a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
Size const n = n_items( a );
int b[n] = {}; // An array of the same size as a.
(void) b;
cout << "Size = " << n << "\n";
}
数组大小的 C idiom,sizeof(a)/sizeof(a[0])
,将接受一个指针作为参数,然后通常会产生不正确的结果。
对于 C++ 11
使用 C++ 11,你可以:
std::extent<decltype(MyArray)>::value;
例:
char MyArray[] = { 'X','o','c','e' };
const auto n = std::extent<decltype(MyArray)>::value;
std::cout << n << "\n"; // Prints 4
直到 C++ 17(在撰写本文时即将发布)C++没有内置的核心语言或标准库实用程序来获取数组的大小,但这可以通过引用数组通过引用函数模板来实现,如如上所示。很好但很重要的一点:模板大小参数是一个 size_t
,与签名的 Size
函数结果类型有些不一致,以适应有时坚持使用 size_t
进行模板匹配的 g ++编译器。
使用 C++ 17 及更高版本,可以使用 std::size
,它专用于数组。