Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size metafunction - is it in boost somewhere?

I found the following template on a blog:

template <typename T, size_t N>
struct array_info<T[N]>
{
    typedef T type;
    enum { size = N };
};

It is an elegant alternative to sizeof(a) / sizeof(a[0]).

A commonly-used construct for getting the size of an array should surely be somewhere in a library. I'm not aware of one. Can anyone tell me this functionality is in the standard libraries somewhere and/or in Boost? Preferably in an easy-to-use and lightweight form.

like image 546
paperjam Avatar asked Nov 24 '11 13:11

paperjam


People also ask

How does sizeof know array size?

sizeof(type) gives you the number of bytes of the type you pass. Now if you pass array then the compiler knows that this is an array and number of elements in it and it just multiplies that many elements with the respective data-type size value.

How do you state the size of an array?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

Can we get size of array at run time?

No. In an array declaration, the size must be known at compile time. You can�t specify a size that�s known only at runtime.

What does size return in array?

array::size() size() function is used to return the size of the list container or the number of elements in the list container.


1 Answers

I eventually found the answer myself - boost::size():

#include <boost/range.hpp>

int array[10];
boost::size(array); // returns 10
like image 106
paperjam Avatar answered Oct 12 '22 02:10

paperjam