Dynamic any-casting in C++

Some time ago I was talking with a coworker and we ended up discussing how to implement an "any" dynamically castable pointer in C++. The rules are:

You can think, for example, of the any type in Go and how you can cast it to an interface U if the original value T implemented U. Turns out this is a tricky problem in C++.

Solving with supertype

If we use a supertype, this seems trivial.

class Object {
public:
    virtual ~Object() = default;
};
#include <cstdio>
#include <memory>

class MyBaseClass : public Object {};
class MyDerivedClass : public MyBaseClass {};
class UnrelatedClass : public Object {};

int main()
{
    std::unique_ptr<Object> any_pointer = std::make_unique<MyDerivedClass>();

    MyDerivedClass *derived = dynamic_cast<MyDerivedClass *>(any_pointer.get());
    MyBaseClass *base = dynamic_cast<MyBaseClass *>(any_pointer.get());
    // Returns nullptr:
    UnrelatedClass *unrelated = dynamic_cast<UnrelatedClass *>(any_pointer.get());

    std::printf("%p %p %p\n", derived, base, unrelated);

    return 0;
}

However, this fails the first requirement:

You can point to any type T using the "any" pointer

We can't point to any type T because we require T : public Object. Since we don't have language support for a global supertype, this solution is not what we want.

Framework: wrapping values within a custom type

For exploring more solutions, let's assemble a little framework. The overall idea will be to create a type any which is an unique pointer (similar to std::unique_ptr) which points to our custom type. However, in order to be able to implement operations within the pointed-to value, we will wrap it with another type, which we will call any_impl<T> which inherits from any_base.

This is the idea:

#include <memory>

class any_base {
public:
    virtual ~any_base() = default;
    // custom methods
};

template <typename T>
class any_impl final : public any_base {
public:
    template <typename... Args>
    any_impl(Args &&...args) : m_value{std::forward<T>(args)...}
    {
    }
    ~any_impl() override = default;
    // custom implementations
private:
    T m_value;
};

class any final {
public:
    template <class ValueType, class... Args>
    explicit any(std::in_place_type_t<ValueType>, Args &&...args)
        : m_ptr{std::make_unique<any_impl<ValueType>>(
              std::forward<Args>(args)...)}
    {
    }

private:
    std::unique_ptr<any_base> m_ptr;
};

template <class T, class... Args>
any make_any(Args &&...args)
{
    return any(std::in_place_type<T>, std::forward<Args>(args)...);
}

Only any needs to be public, meaning we can move any_base and any_impl inside private: within class any. However, for demonstration purposes, I'll keep things separated.

Why typeid doesn't work

What if we cast to void * after checking the typeid and then reinterpret_cast?

#include <memory>
#include <typeinfo>

class any_base {
public:
    virtual ~any_base() = default;
    virtual void *cast(const std::type_info &ty) = 0;
};

template <typename T>
class any_impl final : public any_base {
public:
    template <typename... Args>
    any_impl(Args &&...args) : m_value{std::forward<T>(args)...}
    {
    }
    ~any_impl() override = default;

    void *cast(const std::type_info &ty) override
    {
        if (ty == typeid(T)) {
            return static_cast<void *>(&m_value);
        }
        return nullptr;
    }

private:
    T m_value;
};

class any final {
public:
    template <class ValueType, class... Args>
    explicit any(std::in_place_type_t<ValueType>, Args &&...args)
        : m_ptr{std::make_unique<any_impl<ValueType>>(
              std::forward<Args>(args)...)}
    {
    }

    template <typename T>
    T *cast()
    {
        return reinterpret_cast<T *>(m_ptr->cast(typeid(T)));
    }

private:
    std::unique_ptr<any_base> m_ptr;
};

template <class T, class... Args>
any make_any(Args &&...args)
{
    return any(std::in_place_type<T>, std::forward<Args>(args)...);
}

As you may expect, this doesn't work for supertypes U of T:

#include <cstdio>

class MyBaseClass {};
class MyDerivedClass : public MyBaseClass {};
class UnrelatedClass {};

int main()
{
    any any_pointer = make_any<MyDerivedClass>();

    // Works
    MyDerivedClass *derived = any_pointer.cast<MyDerivedClass>();
    // Doesn't work
    MyBaseClass *base = any_pointer.cast<MyBaseClass>();

    std::printf("%p %p\n", derived, base);

    return 0;
}

If you only need casting to the leaf class, std::any already does this for you as well.

Is this possible?

As far as I can tell, this is only possible with reflection. If you want to solve this puzzle and to learn about reflection syntax, I recommend you pause reading and give it a try!

Solution

The overall idea is: in any_impl<T>, cast(const std::type_info& ty) checks ty against typeid(T) and against typeid(U) for every base class of T, recursively.

This is my solution:

#include <memory>
#include <meta>
#include <type_traits>
#include <typeinfo>

class any_base {
public:
    virtual ~any_base() = default;
    virtual void *cast(const std::type_info &ty) = 0;
};

template <typename T>
class any_impl final : public any_base {
public:
    template <typename... Args>
    any_impl(Args &&...args) : m_value{std::forward<T>(args)...}
    {
    }
    ~any_impl() override = default;
    void *cast(const std::type_info &ty) override
    {
        if (is_derived_from_type_info<T>(ty)) {
            return static_cast<void *>(&m_value);
        }

        return nullptr;
    }

private:
    template <typename Derived>
    static bool is_derived_from_type_info(const std::type_info &ty)
    {
        if (ty == typeid(Derived)) {
            return true;
        }

        if constexpr (std::is_class_v<Derived>) {
            template for (constexpr auto base :
                            std::define_static_array(std::meta::bases_of(
                                ^^Derived,
                                std::meta::access_context::current())))
            {
                constexpr auto base_ty = std::meta::type_of(base);
                if (is_derived_from_type_info<typename[:base_ty:]>(ty)) {
                    return true;
                }
            }
        }

        return false;
    }

    T m_value;
};

class any final {
public:
    template <class ValueType, class... Args>
    explicit any(std::in_place_type_t<ValueType>, Args &&...args)
        : m_ptr{std::make_unique<any_impl<ValueType>>(
              std::forward<Args>(args)...)}
    {
    }

    template <typename T>
    T *cast()
    {
        return reinterpret_cast<T *>(m_ptr->cast(typeid(T)));
    }

private:
    std::unique_ptr<any_base> m_ptr;
};

template <class T, class... Args>
any make_any(Args &&...args)
{
    return any(std::in_place_type<T>, std::forward<Args>(args)...);
}
#include <cstdio>

struct MyBaseClass {};
struct MyDerivedClass : public MyBaseClass {};
struct UnrelatedClass {};

int main()
{
    any value = make_any<MyDerivedClass>();

    std::printf("%p\n", value.cast<MyDerivedClass>());
    std::printf("%p\n", value.cast<MyBaseClass>());
    std::printf("%p\n", value.cast<UnrelatedClass>());

    return 0;
}

As expected, only casting to UnrelatedClass returns nullptr.

Reflection needs C++26. In G++, -freflection is also needed. I have published a repository on GitHub with a more polished version of this solution.

If you come up with a different solution, especially if it is one without reflection (I don't think it's possible, though), it would be cool to know!