|
Boost : |
Subject: Re: [boost] [optional] little addition
From: Niels Dekker - mail address until 2010-10-10 (niels_address_until_2010-10-10_at_[hidden])
Date: 2009-02-27 07:04:45
Arno Schödl wrote:
> I just started using boost::optional, and this proved to be
> generically useful, but I believe is currently not in
> boost::optional:
>
> template< class T, class Tcompatible >
> bool optional_assign(
> T& t, boost::optional<Tcompatible> const& optt) {
> if( optt ) {
> t=*optt;
> return true;
> } else {
> return false;
> }
> }
>
> so you can write
>
> boost::optional< TMyValue > TryToGetT();
> T t;
>
> if( !optional_assign( t, TryToGetT () ) {
> ... other way to get t ...
> }
Are you sure you want to do a copy-assignment of your T? Your example
would typically be more efficient when doing a move-assignment or a swap
instead. What would you think of an optional<T>::swap_if_initialized
member function, so that you can do:
if( ! TryToGetT().swap_if_initialized(t) {
... other way to get t ...
}
Implemented as:
bool swap_if_initialized(T& arg)
{
if ( *this )
{
// Using the Boost Swap utility:
boost::swap(**this, arg);
return true;
}
return false;
}
Kind regards, Niels
-- Niels Dekker http://www.xs4all.nl/~nd/dekkerware Scientific programmer at LKEB, Leiden University Medical Center
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk