More D newb questions.
Fawzi Mohamed
fmohamed at mac.com
Sat May 10 05:00:16 PDT 2008
On 2008-05-10 00:56:33 +0200, Derek Parnell <derek at psych.ward> said:
> On Fri, 9 May 2008 16:01:12 +0200, Fawzi Mohamed wrote:
>
>
>> What you seem to want is an implicit cast of an element to an array
>> with the single element.
>
> I agree that this will cause more problems that it will solve. However, if
> we rephrase your statement slightly ...
>
> I want to be able to cast a single element to an array. What sort of syntax
> (change) would that ability need and cost?
>
> eg.
> T a, b;
> T[] foo = cast(T[])a ~ cast(T[])b;
>
> But that is far to 'wordy' to be usable. I'd like something a lot more
> simple and intuitive. Maybe a new operator so that we don't upset opCat. I
> hereby propose an opJoin operator. It joins two elements to form an array.
>
> T a, b;
> T[] foo = a ~~ b;
> T[] bar = foo ~~ a;
> T[] qwe = b ~~ foo;
>
> Is there ANY way that this SORT OF thing could be made to work in D?
using two test taken from tango.core.Variant
template isArray(T)
{
static if( is( T U : U[] ) )
const isArray = true;
else
const isArray = false;
}
template isStaticArray(T)
{
static if( is( typeof(T.init)[(T).sizeof / typeof(T.init).sizeof] == T ) )
const isStaticArray = true;
else
const isStaticArray = false;
}
template alwaysArrayT(T){
static if (isStaticArray!(T))
alias typeof(T.dup) alwaysArrayT;
else static if (isArray!(T))
alias T alwaysArrayT;
else
alias T[] alwaysArrayT;
}
alwaysArrayT!(T) alwaysArray(T)(T x){
static if (isStaticArray!(T))
return x.dup;
static if (isArray!(T))
return x;
else
return [x];
}
alwaysArray converts any type to a dynamic array, now what you want is
alwaysArray(a)~alwaysArray(b)
this makes sense in generic code, normally you know wether a in an
element or an array and you handle accordingly.
If you want with this you can also implement directly your ~~ and it
would be more efficient (no temporary array for elements).
In D 2.0 it should be nicer to write because the static arrays are more
uniform, and you can also use the traits.
Note that as noted by Janice alwaysArray has a fixed choice of which
array to use when given a scalar, so it cannot coexist with an
overloaded version that uses another array.
Fawzi
More information about the Digitalmars-d
mailing list