|
Boost : |
From: Daniel Frey (daniel.frey_at_[hidden])
Date: 2002-06-24 06:48:52
Hello,
I noticed that boost doesn't have any helper for sizeof_array. The usual
approach is something like
#define sizeof_array( x ) ( sizeof(x) / sizeof(*x) )
The problem is, that it is a potential source of errors if applied to
pointers. Usually, the code that compiles looks like:
<< sizeof_array( s2 ) << endl;
Which outputs
14
1
instead of '14' twice. I therefore wrote a small helper function/class:
#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>
namespace boost
{
template< typename array_t > class sizeof_array_t
{
private:
BOOST_STATIC_ASSERT( ::boost::is_array< array_t >::value );
typedef remove_bounds< array_t >::type element_t;
public:
BOOST_STATIC_CONSTANT( std::size_t, value = sizeof( array_t ) /
sizeof( element_t ) );
};
template< typename array_t > std::size_t sizeof_array( array_t& )
{
return ::boost::sizeof_array_t< array_t >::value;
}
}
This allows using sizeof_array safely, as it doesn't compile for
non-arrays. The only potential drawback I found is, that it's use is a
bit more complicated for static evaluation and sometimes, you need
typeof (hopefully in the next standard!?). Example usage:
#include <iostream>
using namespace std;
int main()
{
double x[] = { 1, 2, 3, 4, 5, 6 };
cout << boost::sizeof_array( x ) << endl;
typedef int[42] X;
cout << boost::sizeof_array_t< X >::value << endl;
// Static use:
enum {
V1 = boost::sizeof_array_t< X >::value,
// Uses gcc-extension '__typeof'
V2 = boost::sizeof_array_t< __typeof( x ) >::value
}
}
What's your opinion? Is it worth to be added somewhere (utility.hpp,
static_assert.hpp, ...)? Is the implementation OK? Any feedback is
welcome...
Regards, Daniel
PS: I'm never sure if 'size_t' or 'std::size_t' is correct :)
-- Daniel Frey aixigo AG - financial training, research and technology Schloß-Rahe-Straße 15, 52072 Aachen, Germany fon: +49 (0)241 936737-42, fax: +49 (0)241 936737-99 eMail: daniel.frey_at_[hidden], web: http://www.aixigo.de
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk