D Paste by KirkMcDonald
Description: Nifty code that works now
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import std.stdio; import std.traits; // GIVEN: A type which may be converted to a number of other types union U { int i; real r; char[] s; } // GIVEN: A template function which may convert that type to its several // convertable types. T convert(T)(U u) { static if (is(T == int)) { return u.i; } else static if (is(T == real)) { return u.r; } else static if (is(T == char[])) { return u.s; } else static assert(false, "Invalid type."); } // GIVEN: A function whose arguments are of these convertable types. void foo(int i, real r, char[] s) { writefln("%s %s %s", i, r, s); } // CREATE: A template function which accepts a collection of the original type // and calls the function with the converted arguments. void apply(alias fn) (U[] u) { ParameterTypeTuple!(fn) t; foreach (i, arg; t) { t[i] = convert!(typeof(arg))(u[i]); } fn(t); } void main() { U[3] u; u[0].i = 12; u[1].r = 5.8; u[2].s = "hello"; apply!(foo)(u); } |