陣列大小型別在編譯時是安全的

#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 ,它專用於陣列。