Boost logo

Boost :

Subject: Re: [boost] [optional] Safe optional
From: Joaquin M Lopez Munoz (joaquin_at_[hidden])
Date: 2014-11-17 12:14:32


Andrzej Krzemienski <akrzemi1 <at> gmail.com> writes:

>
> No, no exceptions.
> The solution is based on the observation that there is a limited number of
> things you can do with optional<T>
>
> optional<int> oi = ...;
>
> 1:
> if (oi) doSomething(*oi);
> else doSomethingElse(); // or nothing
>
> 2:
> if (oi) doSomething(*oi);
> else doSomething(-1); // use default value
>
> 3:
> if (!oi) oi = (int)getIntByOtherMeans();
> doSomething(*oi); // now it is safe

Just to throw some idea in, there's an altenative based on the following
approach: let's assume we have a function f such as

  f(T1,...,T2)->ret

and we have arg1,...argn where the type of argi optional<T1>.
To call f we'd have to do something like

  auto ret=
    arg1&&arg2&&...&&argn?
    f(arg1.get(),...,argn.get()):
    none;

In fact, we could *lift* f so that we write this instead:

  auto ret=lift<f>(arg1,...,argn);

with the same semantics. This is a case of *monadic lifting* as
explained (and implemented) at

  http://bannalia.blogspot.com/2014/03/monadic-lifting-in-c.html

Lifting can be applied to regular functions as well as operator
such as the arithmetic ones (relational operators don't follow the
asme behavior). For the same price, lift<f> can accept any
combination of optional and non-optional args. Not sure this is
a case of interface augmentation that we want to apply to
boost::optional, but I felt like mentioning it at least.

Joaquin M López Muñoz
Telefónica


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk