質問

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::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.

他のヒント

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.

Unfortunately, none that I know of. This would require special support from a compiler because current compilers do not store any sort of metadata that would be required for this sort of reflection

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top