"Kevin Goodsell" <> wrote in message
news:_sEac.9204
> > 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];
> > };
Josh's way is more succint.
> Would this actually be safe?
>
> Just so we're clear, the purpose that I had in mind for this cast
> operator is to allow conversion of a pointer of type Src* to Dest* if
> and only if that conversion is reasonable. How we define "reasonable"
> may be different, but what I had in mind was pointer conversions that
> are guaranteed to give well-defined results -- for example, Any* to
> void*, Any* to unsigned char*, maybe Any* to char*. Also T* to T* would
> probably be good to allow. Same with Derived* to Base*. But the main
> purpose I had in mind was for situations where you have a buffer that
> needs to be passed to a function, and that function expects a different
> type buffer (like char when you have unsigned char).
I don't think Any* to unsigned char * is reasonable. The buffer thing you
mention is one I use myself, and I used reinterpret_cast (there were public
functions for short&, bool&, double&, etc, which called a private function
to do the reinterpret_cast, so I think it's pretty safe). I guess the
newsgroup is the place to try new things

.
> Anyway, isn't it a mistake to assume that the existence of a conversion
> from Src to Dest implies a conversion from Src* to Dest*? For example,
> wouldn't this allow int* to be converted to double*?
Right, it is incorrect. Can't think of the correct way, or if there is one,
short of specialization.