Re: static_cast signed to unsigned
From: Siemel Naran (SiemelNaran_at_REMOVE.att.net)
Date: 03/31/04
- Next message: Jakob Bieling: "Re: delete[] or delete or delete[] * ???"
- Previous message: Keith Thompson: "Re: Challenging macro with default value"
- In reply to: Kevin Goodsell: "Re: static_cast signed to unsigned"
- Next in thread: Kevin Goodsell: "Re: static_cast signed to unsigned"
- Reply: Kevin Goodsell: "Re: static_cast signed to unsigned"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 31 Mar 2004 07:51:21 GMT
"Kevin Goodsell" <usenet2.spamfree.fusion@neverbox.com> wrote in message
news:_4lac.7906
> > Because the fact that T can be static cast to U does not imply that T*
can
> > be static cast to U*.
> I'm loath to use reinterpret_cast (partly because I'm utterly confused
> as to what, if any, guarantees are provided with it). In cases like
> this, I might consider writing a new cast operator:
>
> template<class Dest, class Src>
> Dest pointer_cast(Src)
> {
> return static_cast<Dest>(static_cast<void *>(Src));
> }
>
> Of course this is a terribly unsafe operator. With some work I think you
> could create a reasonably safe version. Maybe you could specialize it
> for the types that are safe -- is there a way to prevent if from being
> instantiated for other types?
To make it safe, I think you can: make the function take pointer types so
that Src is deduced to char rather than char*, use Andrei's trick to enforce
that a conversion from Src to Dest exists.
template<class Dest, class Src>
Dest * pointer_cast(Src * src)
{
typedef char[sizeof(Overload<Dest>::conversion(Src()))-1]
AssertConversion;
return static_cast<Dest *>(static_cast<void *>(src));
}
where
template <class Dest>
struct Overload
{
char (&conversion(...))[1];
char (&conversion(Dest))[2];
};
- Next message: Jakob Bieling: "Re: delete[] or delete or delete[] * ???"
- Previous message: Keith Thompson: "Re: Challenging macro with default value"
- In reply to: Kevin Goodsell: "Re: static_cast signed to unsigned"
- Next in thread: Kevin Goodsell: "Re: static_cast signed to unsigned"
- Reply: Kevin Goodsell: "Re: static_cast signed to unsigned"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|