Aleksey Gurtovoy writes:
 > 
 > The following is a sketch of a potential use case for the newly-accepted and
 > already very useful 'optional' class. 
 > 
 > Suppose you have a pure RAII guard/locker which unconditionally does its
 > job:
 > 
 >     struct RAII_lock
 >         : boost::noncopyable
 >     {
 >         RAII_lock(entity& e);
 >         ~RAII_lock();
 >     };
 >     
 > and you want to write a semantic equivalent to the following
 > 
 >     boost::scoped_ptr<RAII_lock> lock( cond ? new RAII_lock(entity) : 0 );
 >     // ...
 > 
 > expect for the dynamic allocation part. How would you do it? 
 > 
 > IMO the following seems only natural:
 > 
 >     boost::optional<RAII_lock> lock( cond, entity );
 >     // ...
 > 
 > The only problem with the above is that currently you cannot write something
 > like this. It would be nice if we could, IMO.
 > 
 > Thoughts?

* Firstly, this would require optional to be able hold non-copy-constructible
types, whereas the current requirement say "T must be CopyConstructible".

You could drop the "CopyConstructible" requirement if you said that
boost::optional<T> is only itself CopyConstructible/Assignable/Swappable if T
is CopyConstructible. However, this leaves the question of how to get the
value in there in the first place; the answer to which is ...

* Secondly, you would need a templated constructor to allow T to be constructed
using another type.

Or you could initialize it with optional<EntityType>, since this template
constructor does already exist, and already does the "right thing".

* Thirdly, you would need a special custom constructor which takes a conditional.

You could get round it like below:

    boost::optional<EntityType> optionalEntity;
    if(cond)
        optionalEntity.reset(entity);

    // if optionalEntity is not initialized, neither is lock
    // else lock is constructed using the conversion constructor
    boost::optional<RAII_lock> lock(optionalEntity);

You can do this with the current implementation, since the CopyConstructible
requirement isn't actually verified with a concept check, but you'd have to
get the requirement dropped if you were to rely on it (which would probably
mean implementing templated constructor/reset/operator= to avoid _having_ to
use an optional<U> to initialize your optional<T>)

HTH

Anthony
-- 
Anthony Williams
Senior Software Engineer, Beran Instruments Ltd.
Remove NOSPAM when replying, for timely response.

_______________________________________________
Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost

Reply via email to