C++ Logo

std-proposals

Advanced search

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

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Mon, 8 Apr 2024 10:20:45 +0200
That is not portable code. You are using pointer arithmetics and casts.   Of course typeid could have been standardized as pseudo standard library function living in the std namespace. But this is only about usage. Not about implentability.   Your implementation code proofs nothing.   Actually *all* C++ core language features can be implemented by function calls.   (Just write a C++ interpreter, which receives the contents of the source files.)   -----Ursprüngliche Nachricht----- Von:Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Mo 08.04.2024 10:06 Betreff:Re: [std-proposals] Extend std::type_info with more information An:std-proposals <std-proposals_at_[hidden]>; CC:Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>; 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. -- Std-Proposals mailing list Std-Proposals_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2024-04-08 08:20:47