C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 8 Apr 2024 09:06:02 +0100
On Mon, Apr 8, 2024 at 7:29 AM Jens Maurer wrote:
>
> I wasn't asking about this. I was specifically asking about the
> idea that, instead of a built-in operator "typeid", we should just
> have a template get_type_id<T>


Just to give context here:
   We have a core language operator 'typeid' to get the 'std::type_info'.
   I argued a day or two ago here on this mailing list that it should
have simply been a standard library function, i.e. "std::typeid",
instead of an operator.


On Mon, Apr 8, 2024 at 8:01 AM Gašper Ažman wrote:
>
> But again - why? Just use typeid(type) instead of typeid(expression)


Here's how I would have coded 'std::get_type_info' on Linux, macOS, FreeBSD:

#include <cstdint> // intptr_t
#include <typeinfo> // type_info
#include <type_traits> // is_polymorphic, remove_cvref

namespace std {
    template<typename ParamT>
    type_info const &get_type_info(void) noexcept
    {
        // just return the typeinfo of ParamT
        static char const *const p = "13WhateverClass";
        return *(std::type_info*)(&p - 1u);
    }

    template<typename ParamT>
    type_info const &get_type_info(ParamT &&obj) noexcept
    {
        using T = remove_cvref_t<ParamT>;
        if constexpr ( std::is_polymorphic_v<T> )
        {
            void **vtable = *(void***)&obj;
            intptr_t const offset_to_most_derived = (intptr_t)vtable[-2];
            void *const most_derived_object = (char*)&obj +
offset_to_most_derived;
            vtable = *(void***)most_derived_object;
            return *(std::type_info*)vtable[-1];
        }
        else
        {
            return get_type_info<T>();
        }
    }
}

Here it is tested and working up on GodBolt: https://godbolt.org/z/486s9146o

Given that it can be coded as a simple library function, I don't see
why a change was made to the core language to add a new operator.

Received on 2024-04-08 08:06:15