Boost logo

Boost :

From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2000-12-07 19:17:57


Jesse Jones wrote:
> >I hope that is sufficient to speak for the utility of these
> functions. As to
> >triviality, the same could be said for std::pair<>. Sometimes a trivial
> >construct has great advantages in expressive power.
>
> Sure, but I think these two functions impair rather than enhance
> readability. How is:
> derived = polymorphic_downcast <Derived*>(base);
> better than
> derived = dynamic_cast<Derived*>(base);
> assert(derived != NULL);

It's better because it wasn't supposed to be a 'dynamic_cast' in the first
place. It should be

derived = static_cast<Derived*>(base);

because you use 'polymorphic_downcast' only then you KNOW that base actually
points to Derived. But you don't want to deal with a mess you'll get in case
if someone make changes that break your code, so you use
'polymorphic_downcast' to trap that situation.

> It's really only better because polymorphic_downcast doesn't do a
> dynamic_cast in release. But I don't think this sort of
> micro-optimization merits yet another cast operator.

It's not about micro-optimization, it's about showing the intent of code in a
less amount of lines and in the most expressive way. 'polymorphic_downcast'
states that cast to Derived* should always succeed BY DEFINITION, point. An
inlined 'equivalent' with 'dynamic_cast', however, is not so explicit, because
there are several ways to interpret it, and one of them is "...someone was not
ready to handle 'derived == 0' situation at the moment, so he/she put an
assert here", with a possible sequel "...now I have a case when 'derived == 0'
and I really need to proceed, so let's change the assert to "if (derived) {
/**/ }". Also, speaking about expressiveness, consider passing the result of
the cast to a function:

Derived* derived = dynamic_cast<Derived*>(base);
assert(derived != NULL);
foo(derived);

vs.

foo(polymorphic_downcast <Derived*>(base));

I certainly prefer the last form.

--Aleksey


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