
"Matt Calabrese" <rivorus@gmail.com> writes:
On 6/25/06, me22 <me22.ca@gmail.com> 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