Templates: generic "return null;"

Stanislav Blinov stanislav.blinov at gmail.com
Mon Feb 3 02:32:57 PST 2014


On Monday, 3 February 2014 at 10:25:19 UTC, Chris wrote:

>   T[T] attributes;
>   // ....
>   public auto getAttribute(T attr) {
>       if (!(attr in attributes)) {
>         return null; // Doesn't work for numbers!
>       }
>       return attributes[attr];
>     }
> }

One way would be to use std.typecons.Nullable(T) as a return type.

Another would be to retink your design :) Note that for numbers, 
there's no distinct "does not exist" value (well, ok, we have NaN 
for floating point). Neither there is for structs. Generally such 
methods as your getAttribute either throw, or get a second 
optional parameter as hint on what to return when the element is 
not found in the dictionoary.


More information about the Digitalmars-d-learn mailing list