Tuple mixins
Max Samukha
samukha at voliacable.com.removethis
Fri May 11 04:11:24 PDT 2007
On Fri, 11 May 2007 18:43:06 +1000, Daniel Keep
<daniel.keep.lists at gmail.com> wrote:
>
>Max Samukha wrote:
>> The mixin form compiles and works in some cases (in others it fails).
>> Is it legal at all? Is it mentioned anywhere in the specs?
>>
>> The following declares an int array and initializes it to the last
>> element encoded in the mixin string ([3]). Should the mixin fail with
>> an appropriate error or initialize the array to [1, 2, 3]?
>>
>> void main()
>> {
>> int[] arrr = [mixin("1, 2, 3")];
>> writefln(arrr);
>> }
>
>The problem here is that mixins are not direct string mixins. That is,
>they don't simply spit their argument into the AST like a C preprocessor
>macro would.
>
>There are two kinds of string mixins: statement and expression. The one
>above is an expression mixin. Let's look at it a different way:
>
>int[] arr = [( mixin("1,2,3") )];
>
>If you look at it like that, you see that "1,2,3" is not a tuple at all;
>it's a comma-delimited list of expressions which itself evaluates to the
>*last* expression.
>
>If you wanted to actually mix in a tuple, you'd have to be a bit more
>creative:
>
>int[] arr = [mixin("Tuple!(1,2,3)")]; // Note: not tested
>
>I ran across this when I was trying to generate functions with a
>particular name. Turns out this *doesn't* work:
>
>> void mixin(identName)()
>> {
>> // Do stuff
>> }
>
>Basically, simple rule of thumb is: when mixing in an expression,
>mentally put a pair of parentheses around it; it helps you work out
>exactly what it's going to do.
>
> -- Daniel
Using your rule of thumb I discovered that expressions separated by
comma, in parentheses, can be used in contexts where tuples are
allowed. Seems like D is going to have built-in expression tuple
literals. Cool. Has it been discussed anywhere?
void foo(int a /*, int b, int c*/)
{
}
void main()
{
auto tuple = (1, 2, 3);
auto arr = [tuple]; // arr = [(1, 2, 3)] compiles too
foo(tuple);
}
More information about the Digitalmars-d-learn
mailing list