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?
What you are asking for is commonly referred to as Introspection.
The C++ language does not support introspection by itself. You can emulate it, but that is the extent of it.
There is also another issue in the API you propose: how would you formulate the return type of your method ? There is a
boost::anyclass that would be suitable to store the item, but you would not be able to anything useful with it if you do not know its type anyway.