C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Thu, 11 Apr 2024 12:02:51 +0100
On Thu, Apr 11, 2024 at 10:34 AM Mihail Mihaylovwrote:
>
> I strongly disagree with this statement. `Std::any` has value semantics.
> It is very different from `void*`. `Any` is an "open" discriminated union,
> whereas `void *` is a type-erased pointer. Therefore, their use cases
> are quite different.


I agree with Mihail here for two reasons:
    (1) What he says is true - the 'std::any' class also
        has the 'type_info' so it isn't "type-erased" like a void*.
    (2) Even if what he said weren't true, I'd still try to milk
        'std::any' for all its worth.


> The intended use of `any` is just like with any discriminated union - the
> receiver tests the discriminator against one or more options that it knows
> how to handle and performs a cast if it turns out to be one of them. And
> so it actually makes sense for a test against a base class to succeed
> when the `any` contains an instance of a derived class. Of course, as you
> pointed out, the actual cast should pass through the derived type, before
> it gets to the base type.
<snip quote from Frederick>
> As I argued above, yes, the ability for `any_cast` to return a base class
> instance if the contained value is of a derived class is in line with the
> expected use of `any`.
>
> Practical implementability is another story.


Step 1 of implementing it is to be able to see all of the base classes
of the Derived type at runtime having only its type_info. So I propose
adding a new method called 'bases' to std::type_info. At first I
thought this new method should return a pointer to a null-terminated
array of pointers to type_info's, as follows:

    std::type_info const *const *type_info::bases(void) const noexcept;

But Microsoft's array of type_info's isn't laid out the same way as
Itanium's. So we need a special iterator to compensate for this,
"class type_info_iterator", and so the method 'bases' returns a pair
of iterators [first,last) to the type_info's of all the base classes.
I've written it into my paper with implementations for Microsoft and
Itanium:

    http://www.virjacode.com/papers/extend_type_info.htm

And also implemented it on GodBolt:

    https://godbolt.org/z/fbTvbTK11

Received on 2024-04-11 11:03:09