Boost logo

Boost :

Subject: [boost] [array] array_cast helper function
From: herve martin (hervemart1_at_[hidden])
Date: 2009-03-15 10:15:41


   I would present here a new helper function which could take place in the
boost array package since it is related to C-array.

the array_cast() function aims at making cast into C array more friendly
than when using the esoteric syntax T(&)[N]. It can help also to check some
consistency in size between original type and resulting C array.

For some reason reference on C array is almost never used by developers even
if a reference on C array encapsulates more information than just a pointer
on the 1st element. A striking example is that the dynamic allocation of an
array using the new syntax returns a pointer on first element ( int *ptr =
new int[10]; ) although I would expect getting a pointer on an array ( int
(*ptr)[10] = new int[10]; - this syntax fails but is more conform to what we
could expect, even if I must admit that the second syntax is not really
intuitive -).

array_cast() could make reference on C array more common. The main benefit
of array reference is that the size information of the array is encapsulated
in the reference type.
In the previous 'new' example, when writing { int *ptr = new int[10]; } we
have to keep track of the array size by some other way which is not really
smart (#define for example).
array_cast() use will allow the following syntax:
{ int (&carray)[10] = array_cast<int>( *new int[10] ); } which is equivalent
{ int (&carray)[10] = *(int(*)[10]) new int[10] ); }
Size of the C array can be retrieved just with operation sizeof(carray)

In working with array reference rather than with pointer on element array we
could imagine some generic algorithm whose implementation could be optimized
according to the array size.

array_cast() profits also from boost::math::static_gcd function and checks
consistency between sizes.
for example the following code will raise a static assert since type sizes
are not consistent.
struct { char d1; char d2; char d3; } toto;
long (&carray)[1] = array_cast<long>( toto );
Indeed, sizeof( toto ) is rarely equal to sizeof( long[1] ).

3 main functions are defined for array_cast():
array<T,N>( INPUT& data)
array<T>( INPUT& data)
array<N>( INPUT& data)
and its derivatives for const, volatile and const volatile lvalues.

for more details, take a look at the source code
the boost vault repository
and let me know if there is any interest to include it in boost::array.

thanks, herve

Boost list run by bdawes at, gregod at, cpdaniel at, john at