C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Base class reflection

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Tue, 31 Jan 2023 08:03:00 +0000
On Sun, 29 Jan 2023, 21:20 Billy Martin via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> Hello, I would like to propose an addition to the standard library, that
> will allow one to get the immediate base classes of a type, e.g.:
>
> using std::base_class_tuple_t<T> = std::tuple<Bases&...>;
>
> Requires: T is a complete class type.
> Result: an std::tuple type, where the tuple element types are the
> reference types to the immediate base classes of T, if T is a class type
> with base classes, or the empty tuple type otherwise. The references would
> have the same cv-qualification as T.
>
> Why: There is currently no way to do this (that I'm aware of) in C++. It
> would require some compiler magic to implement this type. (note: I don't
> know if it's customary or not to have compiler magic in the standard
> library, maybe this could be a keyword instead, similar to typeid)
>
> This is necessary to solve the problem of mixing polymorphism and type
> erasure. Suppose I have a type erased pointer to some polymorphic object of
> type D. I don't know about the type D. But I know the type B, which is a
> base class of D. I would like to get a B* pointer to D. In general, this
> can't be done as far as I know. (Usually with type erasure you need to know
> the *exact* original type of the type erased thing)
>
> However, if std::base_class_tuple_t exists, then the type erasure system
> could be set up so that you could request a type erased pointer to B, and
> it could search the base classes of D for the type B, and if it finds it
> then perform the pointer conversion and return a type erased pointer to B,
> which would could then extract B* from.
>


What if it doesn't find B? How does this feature help you?

If you already know B a priori, why can't you just check if D is derived
from B (which is easy today) and check if D* is convertible to B* (also
easy)? Why is your proposed feature needed for this?

Received on 2023-01-31 08:03:15