1 /** 2 Additional traits functions. 3 4 Copyright: © 2019 Arne Ludwig <arne.ludwig@posteo.de> 5 License: Subject to the terms of the MIT license, as written in the 6 included LICENSE file. 7 Authors: Arne Ludwig <arne.ludwig@posteo.de> 8 */ 9 module dalicious.traits; 10 11 import std.meta; 12 import std.traits; 13 14 15 /// Select an alias based on a condition at compile time. Aliases can be 16 /// virtually anything (values, references, functions, types). 17 template staticIfElse(bool cond, alias ifValue, alias elseValue) 18 { 19 static if (cond) 20 alias staticIfElse = ifValue; 21 else 22 alias staticIfElse = elseValue; 23 } 24 25 unittest 26 { 27 auto a = 42; 28 auto b = "1337"; 29 30 assert(staticIfElse!(true, a, b) == 42); 31 assert(staticIfElse!(false, a, b) == "1337"); 32 33 int add(int a, int b) { return a + b; } 34 int sub(int a, int b) { return a - b; } 35 36 alias fun1 = staticIfElse!(true, add, sub); 37 alias fun2 = staticIfElse!(false, add, sub); 38 39 assert(fun1(2, 3) == 5); 40 assert(fun2(2, 3) == -1); 41 } 42 43 44 /// Alias of `Args` if `cond` is true; otherwise an empty `AliasSeq`. 45 template aliasIf(bool cond, Args...) 46 { 47 static if (cond) 48 alias aliasIf = Args; 49 else 50 alias aliasIf = AliasSeq!(); 51 } 52 53 unittest 54 { 55 int countArgs(Args...)(Args) 56 { 57 return Args.length; 58 } 59 60 enum answer = 42; 61 62 assert(countArgs(aliasIf!(answer == 42, 1, 2, 3)) == 3); 63 assert(countArgs(aliasIf!(answer == 1337, 1, 2, 3)) == 0); 64 } 65 66 67 /// Evaluates to true if version_ is defined. 68 template haveVersion(string version_) 69 { 70 mixin(` 71 version (` ~ version_ ~ `) 72 enum haveVersion = true; 73 else 74 enum haveVersion = false; 75 `); 76 } 77 78 unittest 79 { 80 version (Posix) 81 static assert(haveVersion!"Posix"); 82 else 83 static assert(!haveVersion!"Posix"); 84 } 85 86 version(unittest) 87 { 88 version = hake_verbenaceous_unwieldily; 89 90 static assert(haveVersion!"hake_verbenaceous_unwieldily"); 91 92 static assert(!haveVersion!"illegitimateness_bottom_mazame"); 93 }