1 /// 2 module rxd.meta2.switch_n; 3 4 import std.format : format; 5 6 /// 7 enum switch2(string pred, string action1, string action2) = 8 q{ 9 static if (__traits(compiles, { enum b = %1$s; } )) 10 { 11 static if (%1$s) 12 %2$s 13 else 14 %3$s 15 } 16 else 17 { 18 if (%1$s) 19 %2$s 20 else 21 %3$s 22 } 23 }.format(pred, action1, action2); 24 25 /// 26 unittest 27 { 28 static assert (switch2!("val", "return 1;", "return 2;") == 29 q{ 30 static if (__traits(compiles, { enum b = val; } )) 31 { 32 static if (val) 33 return 1; 34 else 35 return 2; 36 } 37 else 38 { 39 if (val) 40 return 1; 41 else 42 return 2; 43 } 44 }); 45 46 } 47 48 /// 49 enum switch3(string pred, string action1, string action2, string action3) = 50 q{ 51 static if (__traits(compiles, { enum b = %1$s; } )) 52 { 53 static if (%1$s) 54 %2$s 55 else 56 %3$s 57 } 58 else 59 { 60 %4$s 61 } 62 }.format(pred, action1, action2, action3); 63 64 /// 65 unittest 66 { 67 int func(bool val) 68 { 69 mixin (switch3!("val", "return 1;", "return 2;", "return 3;")); 70 } 71 72 assert (func(true) == 3); 73 assert (func(false) == 3); 74 75 int func2(bool val)() 76 { 77 mixin (switch3!("val", "return 1;", "return 2;", "return 3;")); 78 } 79 80 assert (func2!true == 1); 81 assert (func2!false == 2); 82 } 83 84 85 /// 86 enum switch4(string pred, string do1, string do2, string do3, string do4) = 87 q{ 88 static if (__traits(compiles, { enum b = %1$s; } )) 89 { 90 static if (%1$s) 91 %2$s 92 else 93 %3$s 94 } 95 else 96 { 97 if (%1$s) 98 %4$s 99 else 100 %5$s 101 } 102 }.format(pred, do1, do2, do3, do4); 103 104 /// 105 unittest 106 { 107 int func(bool val) 108 { 109 mixin (switch4!("val", 110 "return 1;", "return 2;", 111 "return 3;", "return 4;")); 112 } 113 114 assert (func(true) == 3); 115 assert (func(false) == 4); 116 117 int func2(bool val)() 118 { 119 mixin (switch4!("val", 120 "return 1;", "return 2;", 121 "return 3;", "return 4;")); 122 } 123 124 assert (func2!true == 1); 125 assert (func2!false == 2); 126 } 127