Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2006-06-25 17:44:33


"Matt Calabrese" <rivorus_at_[hidden]> writes:

> On 6/25/06, me22 <me22.ca_at_[hidden]> wrote:
>>
>> I think it's worth including. It's not all that uncommon; even
>> Freenode/##C++'s channel bot has the following factoid:
>> Don't use sizeof() to get the size of an array, because sizeof() will
>> do the wrong thing if that 'array' is actually a pointer. Use the
>> following instead: template <typename T, size_t N> size_t array_size(T
>> (&)[N]) { return N; }
>
>
> The downside of that is that it doesn't yield a compile-time constant, so
> you can't use it, for instance, as the size of another non-dynamically
> allocated array, nor for template metaprogramming, etc.

That's very important.

> For my projects, I
> do something like:
>
> #include <cstddef>
>
> namespace boost
> {
> template< typename Type, ::std::size_t Size >
> char (&array_size_impl( Type (&)[Size] ))[Size];
> }
>
> #define BOOST_ARRAY_SIZE( array ) sizeof( ::boost::array_size_impl( array )
> )

Sold!

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

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