Search code examples
c++pointersmemorymetaprogrammingtype-deduction

Deducing Primitive Type from Raw Memory and Class Analyzers


Specs:

Compiler: TDM-GCC 5.1.0
OS: Windows 8.1 64-bit

I've done a very thorough search though the C++ Standard Libraries, did some other research, and even peaked at some inline assembly. But I haven't come to a conclusion, so here goes:

Given my compiler, if I know the address and size of a primitive type, is there any way in C++ (up to C++14) to deduce the type from just this information, as well as looking at the raw data in memory (I'm willing to work with inline assembly as well)?

An example:

If I have the following declared:

float x = 1.0f;
int y = 0x3f800000;  //The same raw value in memory as 'x'

is there any way, just by looking at the raw contents of these variables, to deduce their type?

If the simple answer is "no", then please let me give you the context of this question, and maybe you can point me in the right direction.

In short, I'm attempting to write a function that can dissect/analyze a class at runtime (to the furthest extent possible, given that the only real metaprogramming C++ has is templates). I want to be able to determine the member objects of a class given an instance of that class. The "type_traits" library doesn't really help me here, and 'sizeof()' and 'alignof()' offer hints, but it's not enough information to deduce the member objects. And 'typeid()' is useless since I'm working with void pointers, except for grabbing the name of the class.

Crossing my fingers that the C++ ABI/RTTI has somewhat decent metaprogramming.


Solution

  • The simple answer:
    No, this information is not provided during runtime. You can, however, make educated guesses, via alignof(), sizeof(), and knowing what range of values are commonly used for types of certain sizes.

    Or create your own Reflection API.