Hacker News new | ask | show | jobs
by AndrewGreen 5642 days ago
Apologies for blowing my own trumpet, but pound for pound, the neatest thing I've worked with this year is a C++ template I wrote. I like to have the tightest possible scoping of names, but a common pattern makes that difficult. If you've got a function that produces a good value or indicates that it couldn't do so one way to write it is:

  Type theVar;
  if (theFunction(theVar)
    { /*do something with theVar*/ }
theFunction returns true if it set theVar, false otherwise. The problem is that theVar's visibility extends beyond our interest in it. The ZQ template lets me write this:

  if (ZQ<Type> theQ = theFunction())
    { /*do something with theQ.Get()*/}
and all of a sudden I don't have to come up with anywhere near as many meaningful names as before.

To me it's neat because I've found many unanticipated uses for it e.g. wrapping the values in option-specifying structures where a default is cleanly indicated with a default-inited (or subsequently Clear()ed) ZQ, rather than having a separate 'use default' boolean, or 'set default' function.

http://zoolib.svn.sourceforge.net/viewvc/zoolib/trunk/zoolib...

1 comments

You might be interested in boost::optional, even if only as a point of comparison: http://boost.org/doc/libs/1_38_0/libs/optional/doc/html/inde...