Boost logo

Boost :

From: Hamish Mackenzie (hamish_at_[hidden])
Date: 2005-10-18 17:49:07


On Tue, 2005-10-18 at 12:43 -0400, David Abrahams wrote:
> Hamish Mackenzie <hamish_at_[hidden]> writes:
> > True and I think if you could fix it you would find it much easier to
> > sell me on using * and ->. The issue I have with * and -> is that they
> > do not make it clear that the type in question is supposed to be an
> > optional (to someone reading the code). I still can't think of an
> > example where it is desirable to have X * and optional< Y > use the same
> > interface.
>
>
> How about
>
> indirect_iterator<std::vector<optional<T> >::iterator>
>
> ?

Sold!

But now I am worried that I wanted to buy a car (container max size 1)
and instead I am getting a the back half of a bicycle (deep copy
pointer) welded to the front half of a car. Would I be better off with
a bicycle instead?

For instance consider

template< typename Optional_Pointee >
Optional_Pointee add_five( Optional_Pointee x )
{
  if( x != none ) // Does this work for pointers?
  {
    (*x) += 5;
  }

  return x;
}

I imagine if this does not yet work it could be made to. How about...

template< typename OptionalPointee, typename Value_Type >
Optional_Pointee fill( Optional_Pointee x, Value_Type & default_value )
{
  if( x == none )
  {
    x = &default_value; // Does this work with optionals?
  }

  return x;
}

To avoid slicing the constructor and assignment operators could be
something like...

template< typename T >
class safe_optional_arg
{
public:
  // Support pointers
  operator T * () const { return source_; }

private:
  explicit safe_optional_arg( T * source )
    : source_( source )
  {
  }

  T * source_;
};

template< typename T >
inline safe_optional_arg< T > opt( T * source )
{
  return safe_optional_arg< T >( source )
}

class optional
{
public:
  optional( safe_option_arg< T > arg );
  optional & operator = ( safe_option_arg< T > arg );
};

(would need to support smart pointers too)
So that last example would be

template< typename OptionalPointee, typename Value_Type >
Optional_Pointee fill( Optional_Pointee x, Value_Type & default_value )
{
  if( x == none )
  {
    x = opt( &default_value ); // fails if default_value would be sliced
  }

  return x;
}

Hamish


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