C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 3 Apr 2024 09:52:24 +0100
Thiago wrote:
> Try this with this object:
> struct Empty {};
> std::any any = Empty{};


Here you go:

    https://godbolt.org/z/vMW1c7457

Were you expecting it not to work?


> 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.


dynamic_cast has internal functioning similar to what we're talking
about here, but it needs types at compile time.
I think you're suggesting that if I look at the GNU g++ implementation
of 'dynamic_cast', I will be able to code my 'base' function based on
it -- using the type_info to iterate through a list of base classes.
In the past I've worked with std::variant variables where some of the
contained types had a common base, and I think a year or two ago I
proposed "std::variant_common_base" here, but anyway in more than one
scenario when coding in C++, I've found that I have a type-erased
pointer to a Derived type accompanied by its type_info and I want a
pointer to a base class. C++ currently doesn't have this
functionality, and at least one other person here on the mailing list
has asked for this feature:

    https://lists.isocpp.org/std-proposals/2023/03/6082.php


> Whether the C++ language and Standard Library can mandate that is a different
> story.


I think a good first step is to implement it on the 4 big compilers
just to show that it wouldn't be months of work for compiler vendors.
Plus I think we might get away with editing the text of the Standard
in just one place, and maybe even less than a hundred words.

Received on 2024-04-03 08:52:37