|
Boost : |
From: Hamish Mackenzie (hamish_at_[hidden])
Date: 2005-10-17 18:30:29
On Mon, 2005-10-17 at 16:09 -0300, Fernando Cacciola wrote:
> But that's not because optional<> is a pointer, is becasue both optional<>
> and pointer's are somehing else: OptionalPointees.
Let me say first I don't use optional references (yet anyway) and I am
quite happy with your explanation of the need to rebind on assignment.
I am, however, still not convinced that OptionalPointees is
justification for using the interface of a pointer. I still sometimes
think of optional as a vector with a maximum size of one, but I now
think it would be a bad idea to copy member names from std::vector, as
it is likely to cause confusion when using optional< vector< T > >. For
the same reason I think optional< bool > is very problematic with the
current interface (see my earlier post in this thread).
Could the unifying concept OptionalPointee be implemented as free
functions? The user could then decide if they want their code to use a
pointer, an optional or one of either (and that choice would be obvious
to a reader and to the compiler).
Something like
namespace optional_pointee
{
template< typename T >
inline bool has_value( T * p )
{
return p != 0;
}
template< typename T >
inline bool has_value( const optional< T > & o )
{
return o.has_value();
}
template< typename T >
inline T & value( T * p )
{
return *p;
}
template< typename T >
inline T & value( const optional< T > & o )
{
return o.value();
}
}
(I know this is an over simplification, as it would need to support
smart pointers and optional< T & >)
So then you could write...
template< typename Pointer >
inline void f( Pointer p )
{
if( p )
{
std::cout << *p;
}
}
or
template< typename T >
inline void f( const optional< T > & o )
{
if( o.has_value() )
{
std::cout << o.value();
}
}
or
template< typename OptionalPointee >
inline void f( OptionalPointee op )
{
if( optional_pointee::has_value( op ) )
{
std::cout << optional_pointee::value( op );
}
}
Though personally I have not yet come across a situation where I want an
OptionalPointee as template parameter. Is there some common use that I
have overlooked?
Hamish
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk