|
Boost : |
From: Hamish Mackenzie (hamish_at_[hidden])
Date: 2003-09-11 17:31:33
On Thu, 2003-09-11 at 16:35, Fernando Cacciola wrote:
> > It also allows the function to be used with classes without copy
> > constructors
> >
> I don't follow. How so?
>
> > template< typename T >
> > void f( const optional< T > & );
> >
> > restricts T to copyable classes.
> >
> Why? f() as you wrote it, doesn't.
> In fact, in place construction, a new feature of optional<>,
> effectively relaxes the CopyConstructible requirement in some
> cases.
Ok the in place construction stuff is very cool but imposes two
requirements on the caller
1) The caller has to know the function f needs in place construction of
optional to avoid the copy
2) They have to be responsible for constructing the object in question.
Consider the following
class hard_to_copy; // or even impossible
hard_to_copy & x = some_function();
f( x );
or
struct A
{
hard_to_copy x_;
...
} a;
f( a.x_ );
or
void g( hard_to_copy & x )
{
f( x );
}
How would you make f( const optional< T > & ) work?
> Hmmm.. what would be the purpose of a _type_ like null_optional<>?
> I mean, why would you express the idea as a different type instead of
> a different state?
> In which way is it better than an uninitialized optional<>?
Consider
class some_big_class;
template< typename Member_Type = null_optional< some_big_class > >
class A
{
BOOST_STATIC_ASSERT(
is_optional_version_of< some_big_class, Member_Type >::value );
int x_;
Member_Type member_;
};
The size of A< optional< some_big_class > > is going to be much larger
than that of A< null_optional< some_big_class > >.
Also it should be easier for a compiler to eliminate code in the
following...
template< typename T >
enable_if< is_optional_version_of< some_big_class, T >::value, void >
f( const T & x )
{
if( !optional_empty( x ) )
{
...
}
}
void g( const A<> & a )
{
f( a.member_ );
}
> Why do you want to have a function that receives either
> an optional<T> or a T?
> The semantics you seek are expressed by variant< T, optional<T> >,
> though it looks tautological to me.
> Managing this sort of duality is the role of optional<> itself.
Yes something like variant< T, optional< T >, null_optional< T > > but
with _compile_time_ knowledge of which type and only requiring storage
and construction/destruction if it is optional< T >.
Hamish
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk