Boost logo

Boost :

From: Fernando Cacciola (fcacciola_at_[hidden])
Date: 2003-02-27 21:52:51


"Philippe A. Bouchard" <philippeb_at_[hidden]> escribió en el mensaje
news:b3l79e$sl6$1_at_main.gmane.org...
>
> "Philippe A. Bouchard" <philippeb_at_[hidden]> wrote in message
> news:b3hcea$gri$1_at_main.gmane.org...
>
> [...]
>
> > int main()
> > {
> > optional<B> b;
> > optional<C> c;
> >
> > foo(b);
> > //foo(c);
> > }
>
> BTW implicit cast to reference types are not implicit under GCC, they have
> to be called explicitly.

Yes, this is the conformant behaviour AFAIK

>Template casts do not seem to be defined in the
> standard...:
>
> template <typename T>
> struct optional
> {
> template <typename U>
> operator optional<U> const & () const
> {
> return * reinterpret_cast<optional<U> const
*>(static_cast<U
> const *>(reinterpret_cast<T const *>(storage_)));
> }
>
> ...
> };
>
This is seriously wrong:

(a) reinrepret_cast<> has implementation-defined behaviour,
which means that is totally useless in portable code.

(b) you don't need reinterpret_cast<> to obtain a 'T const*'
from the aligned_storage whithin the optional: look at the optional code.

(c) EXTREMELY WRONG: you're converting a pointer to aligned_storage<>
into a pointer to optional<>, !!! but aligned_storage is a _data_member_
of optional!!!

> inline void foo(optional<A> const &)
> {
> }
>
> int main()
> {
> optional<B> b;
>
> //foo(b);
> foo(b.template operator optional<A> const & <A> ());
> }
>
>
> Also, the advantage of casts to reference types is that they do not create
> any temporary objects implicitly.
>
But does not create a new objet either!
A conversion is REQUIRED to give a NEW OBJECT,
otherwise there's no conversion at all: since the object remains exactly
the same, you just BROKE the type system by binding a reference of a
completely unrelated type to the same object.
The only case when you can do something _similar_, that is, when
you can't do a _convertion_ but you can do a _cast_, is when the
reference type (or pointer type, for that matter) is of the type of a
non-ambiguous accesible base-class subobject
(because the object dynamic type is covariant with the
reference/pointer static-type).

>
> I do not see in what it can be dangerous.
>
I do :-)
And I see the danger in reinterpret_cast<>; stay away from it.

>
> What do you think?
>
Please, read my original response to David Held and look carefully at
the optional implementation.
As I said, you could only get half away with such a _conversion_ if you
purposedly _slice_ the U subobject out of a T object
(if U is in fact a subobject of T), and wrap it into a NEW optional.
But you can't go back to a T, so this is not polymorphism, is straight up
conversion, just like converting a long double to a short loosing
along the way all the bits that don't fit.

Fernando Cacciola


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