Confused by struct constructors
Philippe Sigaud
philippe.sigaud at gmail.com
Sat Jan 23 09:09:26 PST 2010
On Sat, Jan 23, 2010 at 14:44, Simen kjaeraas <simen.kjaras at gmail.com>wrote:
> In attempting to create a function to initialize any array of structs in a
> simple manner, I created this code:
>
> void fillArr( uint n, T, U... )( ref T[] arr, U args ) {
> arr[0] = T( U[0..n] );
> static if ( U.length > n ) {
> fillArr!( n )( arr[ 1..$ ], args[ n..$ ] );
> }
> }
>
U is a type . U[0..n] is also a type. You should write:
arr[0] = T(args[0..n]);
Maybe you could also use S.tupleof.length to get the number of fields in S
(or maybe there is a __traits which gives this) and avoid the recursion in
initArray:
void fillArr( T, U... )( ref T[] arr, U args ) {
arr[0] = T(args[0..T.tupleof.length]) ;
static if ( U.length > T.tupleof.length ) {
fillArr( arr[ 1..$ ], args[ T.tupleof.length..$ ] );
}
}
T[] initArray( T, U... )( U args )
if ( U.length > 0
&& (is(typeof( T( args[ 0..T.tupleof.length ] ) ) ) )
&& ( U.length % T.tupleof.length == 0 ))
{
T[] result = new T[ U.length / T.tupleof.length ]; // Create an
array
fillArr( result, args ); // and fill it.
return result;
}
Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100123/ebf37ad2/attachment.htm>
More information about the Digitalmars-d-learn
mailing list