Rather neat way of doing multiple return values
Downs
default_357-line at yahoo.de
Sat Mar 17 10:32:16 PDT 2007
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