Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of Python getattr

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?

like image 799
ulu5 Avatar asked May 01 '12 16:05

ulu5


People also ask

What is Getattr () in Python?

The getattr() function returns the value of the specified attribute from the specified object.

Is Getattr slow python?

Yes, compared to the direct conventional method of accessing an attribute of a given object, the performance of getattr() is slower.

How many arguments Getattr () function receives in Python?

Python getattr() If neither of these exists, an AttributeError is thrown. The getattr() function accepts 2 or 3 values as its parameter.

Does Getattr work with methods?

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.


1 Answers

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.

like image 103
Matthieu M. Avatar answered Sep 16 '22 11:09

Matthieu M.