Alex Rivera | Logout

C++ equivalent of Python getattr

Asked 2012-05-01T16:30:29.127
8

In python, there is a function called getattr which would look like this:

class MyObject():
    def __init__(self):
        self.xyz = 4

obj = MyObject()
getattr(obj, 'xyz')

where the call to getattr would return 4.

Is there a similar way to do this in C++ (Not Visual C++)?

Are there any libraries that have this functionality where I can lookup an object's member variables using a string?

I am trying to find a way to look up public data members in a C++ class that I cannot change. So I cannot use a map to map string literals to values. Maybe like an 'unstringify' with macros?

Edit
Report

1 Answer

5

Nothing like this exists in standard C++. Consider how a struct or class actually works:

struct MyStruct {
  int a;
  int b;
};

Assuming that an int is 32 bits in size, then the location of MyStruct's b is always 4 bytes away from the location of a. That offset arithmetic is handled by the compiler in advance. It's why C is so fast for accessing member data: there is no runtime look-up!

So if I wanted to lookup "b" at runtime, I'd have to find where that is in the struct. And to do that, the compiler would have to generate an offset table to store somewhere in the code. That's a lot of overhead for a language that's meant to not have any hidden inefficiencies.

answered 2012-05-01T16:37:34.543

Your Answer