How is typeid implemented?

566 Views Asked by At

I've read that it is implementation specific depending on your compiler, but what might be one way it is implemented? I am asking mainly because I want to know how it creates a name for a type. I'm relatively knew to programming and to C++ but what I've seen so far, it doesn't seem possible to turn a type into a string before runtime. I was thinking the name generation could be done with macros and token-pasting sort of like this:

#define Put_In_Quotes(input) #input

template<class T>
const char* type_name(T data_type){
   return Put_In_Quotes(T); 
}

But I think this would simply return the literal string "T" instead of the type name. Not to mention it doesn't explain how typeid lets you enter just types and not values for its datatype parameter, eg. typeid(int).name() All answers or guides to more information are greatly appreciated

1

There are 1 best solutions below

0
Dan On

Welcome to SE!

The compiler knows all the possible types your program might employ just like it knows which template forms your program needs instantiated. (As for the particular name strings it generates, different compilers use all sorts of conventions for how they name things internally.)

In simple terms, the typeid operator just returns a type_info object, right? Broadly speaking, that object is essentially all there is to implementing a type's RTTI: a type_info kept in the vtable, which is returned by typeid.

You mentioned you were new to C++, but if you look up how to do a vtable dump for your compiler, you can examine the actual data yourself. The formatting specifics of every compiler will differ, of course, but for a polymorphic type, you'll usually find this info right alongside the rest of that type's vtable data. Depending on how your compiler formats that output, it may look something like an additional struct member of that type and may (usually?) immediately precede or follow the rest of the type data. Static types will have similar data residing elsewhere.