C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Use the exception system to check for bases at runtime

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 02 Apr 2024 17:49:10 -0700
On Tuesday 2 April 2024 08:57:54 PDT Frederick Virchanza Gotham via Std-
Proposals wrote:
> template<class Base>
> Base *base(void *const parg, std::type_info const &ti);
>
> You give this function two pieces of information:
> 1) The address of an object (can be non-polymorphic or polymorphic)
> 2) The type_info of the object
>
> If the object has 'Base' as a base class, it returns a valid pointer
> to the base class. Otherwise it returns a nullptr.

Try this with this object:
struct Empty {};
std::any any = Empty{};

Your code is too convoluted. It looks like you found something and now are
looking for a motivation to use it for. But in that you forgot the simplest
approach: just use the typeinfo that std::any already stores. In all
implementations I am aware of, the RTTI will allow you to walk up and down the
hierarchy chain to confirm if a given type is a base of the stored type. And as
my namesake mentioned, this is logic already implemented and is called
dynamic_cast.

Whether the C++ language and Standard Library can mandate that is a different
story. dynamic_cast could be implemented using something different and
inaccessible from type_info objects (like qobject_cast, which uses the
QMetaObjects).

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Principal Engineer - Intel DCAI Cloud Engineering

Received on 2024-04-03 00:49:13