C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Extend std::type_info with more information

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 10 Apr 2024 12:34:09 -0400
On Wed, Apr 10, 2024 at 11:48 AM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> On Wed, Apr 10, 2024 at 5:12 AM Thiago Macieira wrote:
> >
> > We're still missing the motivation. Why have this information?
>
>
> We want to add a method called "get_base" to "std::any" to check if
> the contained object has a particular base class. That's one use case
> that more than one person has asked for.

So this is just an extension of that `any` idea. If that's the case,
then you shouldn't make a separate proposal; they're just part of the
same thing. Regardless, there was no motivation behind that idea
either, beyond "I personally would use it, so let's do it."

`std::any` is a type-safe, object-based `void*`. It is intended to
replace the usage of `void*` in code that needs to hide types between
interfaces. The main point of the type is to check for mistakes, to
turn undetectable runtime UB into detectable runtime errors. As such,
it should be able to do whatever you could do with a `void*` (minus
the fact that it's object-based). But also, it shouldn't be able to do
anything you *couldn't* do with a `void*` (again, minus being
object-based).

The standard is very clear on this point: if you cast a `T*` to a
`void*`, the *only* viable cast is to *exactly* `T*` (outside of
`char*` shenanigans). Casting to a `B*` which is a base class of `T*`
is UB, unless you cast to a `T*` between the `void*` and the `B*`. So
the thing you want is impossible with `void*`.

And owing to `any`'s design, it should be impossible to do this with
`any` too. This is not a matter of implementability; this is a
question of "what is the intended purpose of this object?".

If you want to change this, then you're asking to change what `any` is
for. And that requires more than just that you want to do it. You need
to argue that this is broadly usable in various use cases that many
programmers encounter and have no viable alternatives. And you also
need to argue that a different type would not be more appropriate,
that `std::any` is the appropriate type for this use case.

Received on 2024-04-10 16:34:22