On Sat, 23 Jan 2010 18:09:26 +0100, Philippe Sigaud <[email protected]> wrote:

On Sat, Jan 23, 2010 at 14:44, Simen kjaeraas <[email protected]>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:

Thank you! Darn, I should have been able to see that.

Maybe you could also use S.tupleof.length to get the number of fields in S

Yeah, I could. However, S might use a different constructor, taking a
different number of arguments.

As for bearophile's concerns:
  struct simpleTuple( T... ) {
    T payload;
  }

  simpleTuple!( T ) ຕ( T... )( T args ) {
    return simpleTuple!( args );
  }

T[] initArray( T, U... )( U args ) if ( is( typeof( T( args[0].tupleof ) ) ) && allSame!( U ) ) {
    T[] result = new T[ U.length ];
    foreach ( i, arg; args ) {
      result[ i ] = T( arg.tupleof );
    }
    return result;
  }

  struct S {
    int n;
    string s;
  }

  auto s = initArray!( S )( ຕ( 1, "a" ), ຕ( 2, "b" ), ຕ( 3, "c" ) );

If ຕ is too hard to type, choose another short name.

--
Simen

Reply via email to