C++ Logo

std-proposals

Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 28 Mar 2023 18:56:43 -0700
On Tuesday, 28 March 2023 06:42:01 PDT Phil Endecott via Std-Proposals wrote:
> 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
> implementation.

The most likely scenario. For IA-64 C++ ABI, I'd expect them to use
abi::__dynamic_cast, not the __do_catch solution.

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

That's dynamic_cast.

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

I think it is the best choice and will be the most likely solution to be
chosen by the implementers. What you want to do is to check whether an object
of a given typeid can be cast to a pointer of another typeid: that's what
dynamic_cast does. The abi::__dynamic_cast function is the type-erased version
of that functionality.

> void* runtime_cast(const typeinfo* t, const typeinfo* u, void* p);
>
> Precondition: p is nullptr or points to an object of type u.
>
> Postcondition:
> 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.

// src2dst has the following possible values
// >-1: src_type is a unique public non-virtual base of dst_type
// dst_ptr + src2dst == src_ptr
// -1: unspecified relationship
// -2: src_type is not a public base of dst_type
// -3: src_type is a multiple public non-virtual base of dst_type
void*
__dynamic_cast(const void* __src_ptr, // Starting object.
             const __class_type_info* __src_type, // Static type of object.
             const __class_type_info* __dst_type, // Desired target type.
             ptrdiff_t __src2dst); // How src and dst are related.


-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DCAI Cloud Engineering

Received on 2023-03-29 01:56:45