C++ Logo


Advanced search

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

From: Phil Endecott <std_proposals_list_at_[hidden]>
Date: Tue, 28 Mar 2023 14:42:01 +0100
Thiago Macieira wrote:
> On Monday, 27 March 2023 10:30:22 PDT Phil Endecott via Std-Proposals wrote:
>> Clearly the throw-catch implementation has a huge overhead. Making it
>> possible to do this portably, i.e. by standardising the functionality
>> provided by std::type_info::__do_catch, would be useful IMO.
> It's unnecessary to standardise __do_catch. std::any is a Standard Library
> type; so long as it is possible in all implementations and reasonably fast in
> most, it can be standardised. You've shown it's possible in all that are
> compliant (disabling RTTI or exceptions isn't compliant), so one hurdle is
> overcome. You've shown it is fast in one implementation, so half of the other
> is done too.

Right. There are various choices:

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

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.

3. Both of the above.

Personally I don't think that (1) is the best choice. Most of the standard
library can be efficiently implemented using the public core language, right?
The disadvantage of (2) is that perhaps it might limit future
innovation in
exception handling?

(*) Sketch of runtime_cast:

void* runtime_cast(const typeinfo* t, const typeinfo* u, void* p);

Precondition: p is nullptr or points to an object of type u.

   if p is nullptr, the return value is nullptr.
   if t == u, the return value is p.
   if t is a base class of u, the return value is a pointer to the
     base object of p of type t.
   else the return value is nullptr.

This seems easy to implement as a wrapper around libstdc++'s
typeinfo::__do_catch, and I think also the similar features in
libc++. I don't know about MSVC.

Regards, Phil.

Received on 2023-03-28 13:42:03