C++ Logo

std-proposals

Advanced search

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

From: Phil Endecott <std_proposals_list_at_[hidden]>
Date: Wed, 29 Mar 2023 20:38:30 +0100
Thanks everyone for your continued feedback.

> 1. Add something like any_base_cast to std::any, and hope that library
> implementers will use private features of the ABI to provide a fast
> implementation.

Arthur O'Dwyer wrote:
> This would be an ABI break: the vendor would have to add a new
> virtual function to the vtable of the internal type used by `std::any`

I'm not convinced that's true, can you elaborate? In fact, I think it's
very nearly possible to implement any_base_cast as a free function;
all that's missing is a method in std::any that returns the void* pointer
to the contained value.


> 2. Add a runtime_cast (*) to the core language, which users can use to
> implement their own Any type with a base cast, and no doubt other uses that
> I've not thought of.

Thiago Macieira wrote:
> That's dynamic_cast.

No, I don't think so. dynamic_cast lets me cast from a base class to a
derived class; what I want is to cast from a derived class to a base
class. That's one of the things that static_cast does at compile time.
Am I missing something?

It is interesting to think about what sort of casting or conversion is
useful in the case of std::any. I do recall once accidentally storing
a double in an any and then trying to retrieve a float, and having
much trouble debugging it.

If base-to-derived casting is possible with little extra effort (e.g.
using __dynamic_cast - I need to look at that, does it handle the cases
that would normally be done at compile time?) then that could also
be useful to some.


Arthur O'Dwyer wrote:
> For Phil's use-case, all we need is:
> template<class B>
> B *runtime_cast(const std::typeinfo& ti, void* p);

Correct.

> I'm also curious whether Phil E has any other use-cases in mind.
> Is there a good reason to provide the super-generalized
> `void *runtime_cast(ti, ti, p)` instead of `B *runtime_cast<B>(ti, p)`?
> What's a situation where you'd want that extra generality?

I have no particular other use-cases.


language.lawyer_at_[hidden] wrote:
> Unlike Itanium ABI, in MSVC, exception handling is not based (only)
> on type_info, and the corresponding structures are not easily obtainable.

Thanks for the detailed info. It seems that this would all be more
difficult for MSVC, though I guess not impossible.


Thanks, Phil.

Received on 2023-03-29 19:38:32