Boost logo

Boost :

From: AlisdairM (alisdair.meredith_at_[hidden])
Date: 2003-12-03 07:31:05


The following seems such an obvious utility, I was surprised I could not
find it in the boost distribution. Could someone point me to the
equivalent if I am missing it. Alternatively, is this worth cleaning up
for a submission?

Basic problem is to know the size of the following array:

int[] aInts = { 1, 2, 3 );

The implementation is simple enough:

template< class T, std::size_t N >
std::size_t size( const T (&)[N] )
{
    return N;
}

assert( size(aInts) == 3 );

We can also overload for boost::array.

I suspect there may be a way to make this a compile-time constant, but
can't figure out the automatic type deduction yet.

If runtime is preferred, then adding an overload for classes with the size
member function allows standard containers to work as well.

template< class T, std::size_t N>
inline std::size_t size( const boost::array<T, N> & )
{
    return N;
}

template< class T >
inline std::size_t size( const T &t )
{
    return t.size();
}

AlisdairM


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk