Rather neat way of doing multiple return values

BCS ao at pathlink.com
Sat Mar 17 11:06:38 PDT 2007


Reply to davidl,

> Nice implementation!!!
> i am thinking about how to get rid of those temp object pointers.

It's all structs and pass by value.

It's a little more verbose than a solution I played with, but I like the 
result better in other regards (mine had a left to right assignment thing 
going).

>> Here's a (imnsho) rather neat implementation of multiple return
>> values  from functions.
>> 
>> import std.stdio;
>> 
>> template tuple(T...) { alias T tuple; } // basics
>>
>> template ptr(T...) { // the typetuple ptr!(T) consists of pointers to
>> the types in T
>> static if (T.length>1) alias tuple!(T[0]*, ptr!(T[1..$])) ptr;
>> else alias T[0]* ptr;
>> }
>> struct multival(T...) { /// Simple holder for multiple values
>> tuple!(T) v=void;
>> static multival!(T) opCall(T t) { multival!(T) res=void; foreach (i,
>> e; t) res.v[i]=e; return res; }
>> }
>> struct ptrlist(T...) { /// List of pointers to variables
>> tuple!(ptr!(T)) v=void;
>> static ptrlist!(T) opCall(inout T t) {
>> ptrlist!(T) res=void;
>> foreach (i, e; t) res.v[i]=&t[i]; // Ignore e because I can't make
>> it inout anyway.
>> return res;
>> }
>> void opAssign(multival!(T) res) {
>> foreach (i, e; res.v) *v[i]=e;
>> }
>> }
>> multival!(int, float) test() { return typeof(test())(2, 3.0); }
>> 
>> ptrlist!(T) list(T...)(inout T v) { return ptrlist!(T)(v); }
>> 
>> void main() {
>> int e=4;
>> float f=5;
>> list(e, f)=test;
>> writefln(e, ", ", f); // 2, 3
>> }
>> Have fun! :D
>> 





More information about the Digitalmars-d mailing list