Boost logo

Boost :

From: Fernando Cacciola (fernando_cacciola_at_[hidden])
Date: 2002-11-21 16:14:32


"Dirk Gerrits" <dirk_at_[hidden]> wrote in message
news:arjgo5$o25$1_at_main.gmane.org...
> Fernando Cacciola wrote:
>
> [snip]
>
> > void recieve_async_message()
> > {
> > optional rcv ;
> > while ( !!(rcv = get_async_input()) && !timeout() )
> > output(*rcv);
> > }
>
> [snip]
>
> Maybe it's a minor point, but I think the !! is really ugly. Have you
> considered the safe_bool idiom that's used in some other Boost
> libraries? (smart_ptr to name one.)
>
Yes, I did.
safe_bool (among other alternatives) was rejected because of the following
(this specific point is explained in detail on the documentation)

void foo()
{
  optional<bool> opt = get_some();
  bool is_it = opt;
}

What is the intention of 'is_it'?
Does it refer to the 'value' of 'opt', or to its initialized state?

The problem is that safe_bool allows for a conversion to bool in certain
contexts, but this violates the design premise that there is no implicit
conversion from optional<T> to T for the case when T=bool.

With the current design, the above will fail to compile, requiring the user
to disambiguate the meaning by choosing either:

  bool is_it_initialized = !!opt;
  bool is_it_true = *opt ;

For similar reasons, the following is not supported either:

if ( opt == 0 ) or if ( opt != 0 )

But if you really dislike the syntax, there is an alternative spelling:

  if ( peek(opt) ) ....

peek() returns a pointer to the optional value if it is initialized, or NULL
if it isn't. Such a pointer can be directly used in a boolean context with
the expected meaning.

--
Fernando Cacciola

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