Confused by struct constructors
Simen kjaeraas
simen.kjaras at gmail.com
Sat Jan 23 05:44:52 PST 2010
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
More information about the Digitalmars-d-learn
mailing list