C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Get base class from std::any

From: Thiago Macieira <thiago_at_[hidden]>
Date: Fri, 31 Mar 2023 11:01:08 -0300
On Wednesday, 29 March 2023 16:54:11 -03 Arthur O'Dwyer via Std-Proposals
wrote:
> dynamic_cast can also cast from derived to base, and also "sideways" — all
> the different directions.
> But the big thing you want, that `dynamic_cast` can't do, is that you want
> to cast from `void*`: you have a pointer to an object where *you don't know
> its static type at compile time*. `dynamic_cast` cannot deal with that kind
> of thing. Specifically, see
> https://quuxplusone.github.io/blog/2022/12/01/chimeric-ptr/#solution-2-open-> coded-dynamic_cast-via-root-object-type

Right.

While dynamic_cast<> itself can't do this, the runtime backend of that C++
construct must, because it must get a type-erased pointer to the source
object, a representation of what that pointer is and a representation of what
we want to get as a result. The IA-64 C++ ABI implementation of that is
abi::__dynamic_cast and those two representations are std::type_info pointers
(specifically __class_type_info because the compiler needs no help if either
source or destination isn't one).

I don't know how MSVC implements this. But we can find out: with a little help
from Godbolt at <https://msvc.godbolt.org/z/e9E4KbWh7>, we see a call to
__RTDynamicCast, that decodes to:

  return __RTDynamicCast(ptr, 0, `??_R0?AUBase@@@8`, `??_R0?AUDerived@@@8`);

Those ?_R0 types demangle as "RTTI Type Descriptor" and, as can be seen in the
g() function, are what typeid() returns.

So this *should* be possible.
-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-03-31 14:01:12