Templates: generic "return null;"

Chris wendlec at tcd.ie
Mon Feb 3 06:09:12 PST 2014


On Monday, 3 February 2014 at 12:25:16 UTC, Dicebot wrote:
> You have forgot to mention what behavior you are actually 
> trying to achieve ;) Common not-so-meaningful value is simply 
> T.init , but there can be no such thing as generic sentinel.
>
> If you need cheap and simple way to figure out that attribute 
> was missing, change API to return value by out parameter and 
> turn normal return value into boolean success flag.

Thanks. T.init actually does the trick. The behavior:

auto name = myStruct.getAttribute("name");

if (name == "bla") {
   // do something
} else {
   // do something else
}

or (theoretically):

auto second = myStruct.getAttribute(1.0);

if (second > 1.5) {
   // do something
} else {
   // do something else.
}

I haven't got a use case for the second example, but it might be 
handy for data analysis and I wanted to test how far you can go 
with templates.

The reasoning behind it is that

string name;
try {
   name = myStruct.getAttribute("name");
} // ...

is a bit awkward an OTT. I'd prefer to introduce 
hasAttribute("name") instead, if I want to be sure it exists.

if (myStruct.hasAttribute("name))
   name = myStruct.getAttribute("name");



More information about the Digitalmars-d-learn mailing list