Re: static_cast signed to unsigned

From: Siemel Naran (SiemelNaran_at_REMOVE.att.net)
Date: 03/31/04


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];
};



Relevant Pages

  • Re: is strncpy useful at all?
    ... > You return a pointer to the terminating null byte of 'dest'. ... char* tstrncpy; ... void runTest(FP_STRNCPY fp, char* dest, char* src, size_t maxlen, ... runTest(tstrncpy, dest, src, sizeof src - 1, DEST_SIZE); ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Function call evaluation order
    ... char *strcpy(char *dest, char *src) ... dest and src are different objects. ... gave a nice view of "undefined" calling sequence (and that explanation I can ...
    (microsoft.public.vc.language)
  • Re: Function call evaluation order
    ... char *strcpy(char *dest, char *src) ... if the post increments are supposed to be evaluated sequentially the ... dest and src are different objects. ...
    (microsoft.public.vc.language)
  • Re: The Indexed Instruction Problem Solved!
    ... Mode" uses half the opcode space for regular/supplementary operations, ... register as register 0 and the source register any of the eight ... 0001 dest: 0 src: 1 ...
    (comp.arch)
  • Re: Function call evaluation order
    ... char *strcpy(char *dest, char *src) ... dest and src are different objects. ... int main ...
    (microsoft.public.vc.language)