Quick actions

cmd+k|ctrl+k

Navigation

Languages

Arrays / Array size type safe at compile time / Essential C++

Snippet info

Language

Cpp

Visibility

public

Author

kkowalczyk

Created

2019-03-27T06:44:34Z

Updated

2019-03-27T06:44:34Z

#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";
}
INFO