Array size type safe at compile time

suggest change
#include <cstddef>     // size_t, ptrdiff_t

using Size = ptrdiff_t;

template< class Item, size_t n >
constexpr auto n_items( Item (&)[n] ) noexcept
    -> Size
{ return n; }

#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";
}
Size = 10

The C idiom for array size, sizeof(a)/sizeof(a[0]), will accept a pointer as argument and will then generally yield an incorrect result.

For C++11

using C++11 you can do:

std::extent<decltype(MyArray)>::value;

Example:

#include <iostream>

int main(int argc, char **argv)
{
    char MyArray[] = { 'X','o','c','e' };
    const auto n = std::extent<decltype(MyArray)>::value;
    std::cout << n << "\n";
}
4

Up till C++17 C++ had no built-in core language or standard library utility to obtain the size of an array, but this can be implemented by passing the array by reference to a function template, as shown above. Fine but important point: the template size parameter is a size_t, somewhat inconsistent with the signed Size function result type, in order to accommodate the g++ compiler which sometimes insists on size_t for template matching.

With C++17 and later one may instead use std::size, which is specialized for arrays.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents