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?
The getattr() function returns the value of the specified attribute from the specified object.
Yes, compared to the direct conventional method of accessing an attribute of a given object, the performance of getattr() is slower.
Python getattr() If neither of these exists, an AttributeError is thrown. The getattr() function accepts 2 or 3 values as its parameter.
Okay, so it's cool that you can use getattr to get methods as well as properties, but how does that help us? Well, this can definitely be useful in keeping your code DRY if you have some common logic surrounding branching method calls.
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::any
class 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With