C++ Logo


Advanced search

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

From: Mihail Mihaylov <mihail.mihailov_at_[hidden]>
Date: Thu, 11 Apr 2024 15:03:30 +0300
On Thu, Apr 11, 2024 at 2:35 PM Tiago Freire via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Again, the "how" is the wrong thing here, it’s a trivial non-issue. The
> "why" is the problem.

The intended usage of `std::any` is to pass it to some code which checks
whether the contained value is of some type which the code knows how to
handle. It seems natural that code which knows how to handle some type,
should also be able to handle all derived types. So, if some code asks the
`any` whether it contains a `Base` instance, and any answers that it does
not, when in fact it contains a `Derived` instance, this is arguably
counterintuitive. Suppose we have a function:

void foo(Base);

We can pass instances of classes that are derived from `Base` to `foo()`,
as long as `Base` is copy-constructible. And `foo()` doesn't need to know
about any of the derived classes, only the caller needs to know about the
derived class. Compare this to:

void HandleBase(any a)
    if (a.type() == typeid(Base)) {
        Base b = any_cast<Base>(a);


This function will only work for the base class. To make it work for
derived classes we need to add to it checks for all derived classes. Not
only is this wasteful, but it also means that this function needs to be
updated every time a new derived class is added. Even worse, the
definitions of some or all derived classes might be unavailable at the
definintion site of the function. Allowing upcasts for `any` would allow us
to write:

void HandleBase(any a)
    if (a.is_a(typeid(Base))) {
        Base b = any_upcast<Base>(a);


That's why I believe that the general direction of the proposal is not
without reasonable motivation.

This electronic communication and the information and any files transmitted 
with it, or attached to it, are confidential and are intended solely for 
the use of the individual or entity to whom it is addressed and may contain 
information that is confidential, legally privileged, protected by privacy 
laws, or otherwise restricted from disclosure to anyone else. If you are 
not the intended recipient or the person responsible for delivering the 
e-mail to the intended recipient, you are hereby notified that any use, 
copying, distributing, dissemination, forwarding, printing, or copying of 
this e-mail is strictly prohibited. If you received this e-mail in error, 
please return the e-mail to the sender, delete it from your computer, and 
destroy any printed copy of it.

Received on 2024-04-11 12:03:46