C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::any::base

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Tue, 16 Apr 2024 13:03:27 +0200
That ambigious base classes can be only detected at runtime, also hints that casting any to a base class is probably quite an expensive operation (compared to dynamic_cast).   Mihail: "Then why would it be good practice, if we transform these functions to take in an any* or any&, to force them to perform a widening any_cast to polymorphic_value<A> followed by a dynamic_cast<B&> or dynamic_cast<C&> respectively?"   Normally the complicated double casts (any_cast + dynamic_cast) are not needed: In many situations you would just transfer a polymorphic_value<A> without std::any.   But just in case, in those situations (where also totally different types are transferred), it would be best practice to chain both casts exactly for the following reasons:  - it is more performant (no scan through inheritance hierarchies for each cast needed)  - ambiguous base classes A (for B and/or C) would be detected at compile-time         Yes, at runtime in can be detected, but not at compile-time. dynamic_cast can (at least sometimes or always) detect this at compile-time.   <source>:12:5: error: ambiguous conversion from derived class 'D' to base class 'A': class D -> B -> A class D -> C -> A 12 | dynamic_cast<A&>(d); | ^~~~~~~~~~~~~~~~~~~ 1 error generated.  

Received on 2024-04-16 11:03:29