Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard name (template or macro) to replace ARRAY_SIZE, _countof, etc yet?

Tags:

c++

arrays

I'm not talking about std::array or anything, just classic vanilla C/C++ arrays. I'm aware of the various ways ARRAY_SIZE / _countof could be implemented, I'm just wondering if they've managed to standardize a name for this yet (under std:: I assume). If not is there a proposal for it?

like image 304
VoidStar Avatar asked Mar 16 '15 04:03

VoidStar


1 Answers

Current workaround

std::extent - the size of arrays

If you are working with native arrays you can use std::extent from <type_traits>, which is used to yield the number of elements in the Nth dimension of an array (defaulting to the first).

int a1[1024];
int a2[std::extent<decltype(a1)>::value]; // int[1024]

A little bit of indirection (generic solution, not just arrays)

There isn't a single name that can act as a replacement for what you are describing, but since C++11 one can use std::begin and std::end to get iterators for a suitable entity, and together with std::distance you have a "superb" way of getting the size of something which has the suitable qualities.

int a1[1024];
auto n = std::distance (std::begin (a1), std::end (a1)); // 1024


The drawback with the above solution is that none of the three functions are constexpr in C++11, and even in C++14 std::distance is still not constexpr (the other two are).

This means that the solution cannot be used in contexts which require a constant-expression.

If you are sure you are working with an entity that provides RandomAccessIterators, one workaround for the workaround would be to use std::end (e) - std::begin(e) if a constant-expression is required (C++14).



Looking into the future

N4280 proposes that we add std::size to the standard library, effectively being exactly what you are looking for.

int a1[1024];
auto n = std::size (a1);

If all goes as planned we will have it in C++17.

like image 97
Filip Roséen - refp Avatar answered Oct 18 '22 20:10

Filip Roséen - refp