How do I pass a type as parameter in this method?

Ali Çehreli acehreli at yahoo.com
Mon Dec 18 23:54:02 UTC 2017


On 12/18/2017 02:58 PM, Marc wrote:
> Imaginary code:
> 
>> int index = FirstOrDefault!(int)(__traits(getAttributes, C.a));
> 
> In that case, if the tuple is empty, the value is the int's type default 
> value.
> 
> The method is defined as  following:
> 
>> template FirstOrDefault(X)(T...) {
>>     static if(T.length > 0) {
>>         enum FirstOrDefault = T[0];
>>     } else {
>>         enum FirstOrDefault = X.init;
>>     }
>> }

template FirstOrDefault(D) {
     template FirstOrDefault(T...) {
         static if(T.length > 0) {
             enum FirstOrDefault = T[0];
         } else {
             enum FirstOrDefault = D.init;
         }
     }
}

template FirstOrDefault_2(T...) {
     static if(T.length > 1) {
         enum FirstOrDefault_2 = T[1];
     } else {
         enum FirstOrDefault_2 = T[0].init;
     }
}

template FirstOrDefault_3(D) {
     template of(T...) {
         static if(T.length > 0) {
             enum of = T[0];
         } else {
             enum of = D.init;
         }
     }
}

void main() {
     // This one requires an alias because I could not get rid of "Error:
     // multiple ! arguments are not allowed".
     alias IntDefault = FirstOrDefault!int;
     static assert (IntDefault!() == 0);
     static assert (IntDefault!([1], "hello") == [1]);
     static assert (IntDefault!("world", 1.5) == "world");

     // This one puts everything into the same argument list
     static assert (FirstOrDefault_2!(double, "yo") == "yo");
     import std.math;
     static assert (isNaN(FirstOrDefault_2!(double)));

     // This one invents .of for an arguably more readable syntax
     static assert (FirstOrDefault_3!int.of!(7) == 7);
     struct S {
         int i = 42;
     }
     static assert (FirstOrDefault_3!S.of!().i == 42);
}

Ali


More information about the Digitalmars-d-learn mailing list