简体   繁体   English

C ++相当于Python的getattr

[英]C++ equivalent of Python getattr

In python, there is a function called getattr which would look like this: 在python中,有一个名为getattr的函数,它看起来像这样:

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

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

where the call to getattr would return 4. 对getattr的调用将返回4。

Is there a similar way to do this in C++ (Not Visual C++)? 在C ++(非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. 我试图找到一种方法来查找我无法更改的C ++类中的公共数据成员。 So I cannot use a map to map string literals to values. 所以我不能使用地图将字符串文字映射到值。 Maybe like an 'unstringify' with macros? 也许像宏的'unstringify'?

What you are asking for is commonly referred to as Introspection . 你要求的通常被称为内省

The C++ language does not support introspection by itself. C ++语言本身不支持内省。 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 ? 您建议的API中还有另一个问题:您将如何制定方法的返回类型? 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. 一个boost::any类,将适合存储的项目,但你不能够任何有用的事情,如果你不知道它的类型呢。

Nothing like this exists in standard C++. 标准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 . 假设int大小为32位,那么MyStructb的位置总是距离a的位置4个字节。 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! 这就是为什么C访问成员数据的速度如此之快:没有运行时查找!

So if I wanted to lookup "b" at runtime, I'd have to find where that is in the struct. 因此,如果我想在运行时查找"b" ,我必须找到结构中的位置。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM