On Sun, 26 Mar 2023, 13:29 Phil Endecott via Std-Proposals, <std-proposals@lists.isocpp.org> wrote:
Dear Experts,

#include <any>
#include <cassert>

class Base {};
class Derived: public Base {};

void f()
  Derived d;
  std::any a{ d };
  auto p = std::any_cast<Base>(&a);
  assert(p);  // Fails

To access a std::any's contained value we need to know its exact type;
we cannot access it knowing only a base type.

What would it take to make this possible?

Essentially, if we imagine std::any to be something like:

class any
  type_info type;
  void* ptr;

So we could add something like:

template <typename T>
T* any_base_cast(any* a)
  if (is_base_of(typeid(T),a.type)) return some_cast<T*>(a.ptr);
  else return nullptr;

There are a couple of issues with that!

1. We need a run-time is_base_of, which doesn't currently exist.

2. There isn't a suitable cast from void* to the base type. (In particular, it's
clear that in the case of multiple inheritance we will need to apply an offset to
get the correct base class.)

Questions for the experts:

* Am I right that this is not possible with the current core language?

* I have the feeling that the run-time information needed to implement
the missing is_base_of and cast needed here may already exist to
support language features like member pointers and exceptions. Is
that true?

Yes, I think we discussed this recently, possibly on this list. It's certainly possible on Itanium. Obviously it wouldn't work for implementations that have been made noncompliant by disabling rtti and /or exceptions. 

* Do any of the existing introspection proposals help with this?

Very unlikely. Introspection is compile time, this is runtime.