C++ Logo


Advanced search

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

From: Phil Endecott <std_proposals_list_at_[hidden]>
Date: Sun, 26 Mar 2023 18:29:51 +0100
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?

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

Regards, Phil.

Received on 2023-03-26 17:29:52