Boost logo

Boost :

From: Darin Adler (darin_at_[hidden])
Date: 1999-09-20 12:23:40


> Do you have a proof, a justification, an
> explanation, or an example ?

Yes. There was a lot of that in my original message. (Please read it.) Here
is a repeat of an excerpt (slightly updated):

    template <class Derived, class Base>
    inline Derived new_polymorphic_downcast(CastFrom* from)
    {
        Derived result(static_cast<Derived>(from));
        assert(dynamic_cast<Derived>(from) == result);
        return result;
    }

Here's an example of what's less powerful about the current implementation.
An error that my suggested implementation catches that the current
implementation misses.

    struct B {
        virtual ~B() { }
    };

    struct D1 : B { };
    struct D2 : B { };
    struct D3 : D1, D2 { };

    int main()
    {
        D3 od3;
        D1* pd1(&od3);
        B* pb(pd1);

        // The following succeeds, because the dynamic_cast does
        // a successful cross-cast, even though the static_cast gets
        // it wrong. You don't get an assert.
        polymorphic_downcast<D2*>(pb);

        // The following fails, because it notices that dynamic_cast
        // has returned something different from what static_casts
        // returned. It's good that it fails because the result
        // returned above from polymorphic_downcast is bad.
        new_polymorphic_downcast<D2*>(pb);
    }

>> - want cast that works like static_cast<>, but only for casting from
>> void* since that's a common reason to use it
>
> Well, void* to X* conversion is just another
> THIS-IS-REALLY-A<X>, which is generally done
> by static_cast.

Most casts are THIS-IS-REALLY-A<X>. For example, polymorphic casts are, and
legal uses of const_cast are too. That doesn't seem like a compelling
argument against the void pointer cast. The more-specific cast makes it
clearer what is going on.

When I see a particular use of casts that's very common in my code, I want
to use a more-specific cast, so I can search for the more-unusual cases. As
C. Green said, these all come from my experience.

I don't want a separate cast for every single type conversion I do. But I do
want different casts for the major categories of type conversions that have
different properties.

    -- Darin


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