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

I'm not talking about std::array or anything else, just classic vanilla C / C ++ arrays. I know about different ways to implement ARRAY_SIZE / _countof , I just wonder if they managed to standardize the name for this yet (in std:: I assume). If there is no suggestion for this?

+8
c ++ arrays
source share
1 answer

Current workaround

std :: extent - size of arrays

If you work with your own arrays, you can use std::extent from <type_traits> , which is used to get the number of elements in the N-dimensional size of the array (the first by default).

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

A little touch (general solution, not just arrays)

There is not a single name that could serve as a replacement for what you are describing, but since C ++ 11 you can use std::begin and std::end to get iterators for a suitable object and together with std::distance you have an “excellent” way to get the size of what has the right qualities.

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


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

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

If you are sure that you are working with an entity that provides RandomAccessIterators, one way to work around the solution is to use std::end (e) - std::begin(e) if you need a constant expression (C ++ 14).



A look into the future

N4280 suggests adding std::size to the standard library, in fact being exactly what you are looking for.

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

If everything goes according to plan, we will have it in C ++ 17.

+9
source share

All Articles