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..$ ] );
  }
}

T[] initArray( T, uint n = U.length, U... )( U args ) if ( n > 0 ) {
  static if (
// ( __traits( compiles, T( args[ 0..n ] ) ) ) && // Same as below. Added for completeness. ( is( typeof( T( args[ 0..n ] ) ) ) ) && // If we can instantiate a struct with this ( U.length % n == 0 ) // and it matches the number of arguments,
      ) {
    T[] result = new T[ U.length / n ];         // Create an array
    fillArr!( n )( result, args );              // and fill it.
    return result;
  } else {
return initArray!( T, n-1, U )( args ); // Didn't work. Try another parameter count.
  }
}

However, upon testing it with this code:

struct S {
  int n;
  string s;
}
auto s = initArray!( S )( 1, "a", 2, "b", 3, "c" );

I get this error:

foo.d(34): Error: cannot implicitly convert expression ((int _param_1, string _param_2)) of type (int _param_1, string _param_2) to int


The problem is apparently on this line:
  arr[0] = T( U[0..n] );
Though I am confuzzled as to why it does not work ( it works in initArray, line 2 ). Any ideas?

--
Simen

Reply via email to