www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Surprising interaction of tuples and slicing

reply Ben Jones <fake fake.fake> writes:
I was doing some metaprogramming where I wanted to make a slice 
of a type:

alias Tbasic = int;
pragma(msg, Tbasic);
alias Tbasica = Tbasic[];
pragma(msg, Tbasica);

//prints int, int[]

And things worked fine until I attempted the same thing on what 
happened to be a tuple of 1 element:


alias Ts = AliasSeq!int;
pragma(msg, Ts);
alias Tsa = Ts[];
pragma(msg, Tsa);
//prints (int), (int)

which confused me until I realized that the [] was slicing the 
tuple.  Note, you can add as many [] as you want since it's 
basically a no-op.

pragma(msg, Ts[0][]); //prints int[]

Is there any use for this behavior?  It seems like it might be 
worth warning like "slicing a tuple is a no-op"

Anyway, figured I'd post here for posterity since I was confused 
by it for a while.
May 07 2020
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 5/7/20 8:33 AM, Ben Jones wrote:> I was doing some metaprogramming 
where I wanted to make a slice of a type:

[...]

 alias Ts = AliasSeq!int;
 pragma(msg, Ts);
 alias Tsa = Ts[];
 pragma(msg, Tsa);
 //prints (int), (int)

 which confused me until I realized that the [] was slicing the tuple.
 Note, you can add as many [] as you want since it's basically a no-op.
[...]
 Is there any use for this behavior?
Slicing an alias sequence is definitely useful e.g. in recursive templates: alias car = T[0]; // (head) alias cdr = T[1..$]; // (tail)
 It seems like it might be worth
 warning like "slicing a tuple is a no-op"
The trouble seems to be when slicing the entire tuple. Even in that case, printing a warning would not be desired in some situations ironically in generic code where e.g. T[0..$] may appear, which is the same as T[]. Ali
May 07 2020
parent Ben Jones <fake fake.fake> writes:
On Thursday, 7 May 2020 at 23:07:40 UTC, Ali Çehreli wrote:

 The trouble seems to be when slicing the entire tuple. Even in 
 that case, printing a warning would not be desired in some 
 situations ironically in generic code where e.g. T[0..$] may 
 appear, which is the same as T[].

 Ali
I agree T[0..$] and T[] mean the same thing and the first could come up naturally, but if there's never a useful cased spelled with T[], then it would be detectable and nice to issue a warning.
May 08 2020