Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-09-14 11:09:52

From: "Fernando Cacciola" <fcacciola_at_[hidden]>
> From: Peter Dimov <pdimov_at_[hidden]>
> > I apologize if this has already been discussed, but did you consider the
> > idiom (often used with dynamic_cast)
> >
> > optional<T> opt;
> >
> > if(T * pt = opt.get())
> > {
> > // initialized, use pt
> > }
> > else
> > {
> > // not initialized, no pt in scope
> > }
> >
> This is already supported.
> I've added .get() precisely in order to support this idiom, but I've been
> kind of reluctant to talk about it.
> It usage is *barely* mentioned in the documentation included in the
> I'm not sure if I would encourage this idiom since it uses a member
> function, and I'm not very fond of using member functions for general
> classes -which could be replaced for something similar-

Well, the emphasis is not on the 'get' member function. You could easily
provide a free function instead.

The important thing about the idiom is that it checks for initialized
optional<T> _and_ retrieves a pointer to T at the same time, so - assuming
that you follow the idiom - you can't access an uninitialized optional by
mistake (since the pointer is not in scope in the 'else' clause.)

Peter Dimov
Multi Media Ltd.

Boost list run by bdawes at, gregod at, cpdaniel at, john at