相当于Python getattr的C ++ [英] C++ equivalent of Python getattr

查看:129
本文介绍了相当于Python getattr的C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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')

getattr的调用将返回4.

where the call to getattr would return 4.

在C ++(不是Visual C ++)中是否有类似的方法?

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?

我试图找到一种方法来查找我无法更改的C ++类中的公共数据成员.因此,我无法使用映射将字符串文字映射到值.也许像是用宏取消字符串化"?

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?

推荐答案

您要的内容通常称为自省.

C ++语言本身不支持自省.您可以模拟它,但这就是它的范围.

The C++ language does not support introspection by itself. You can emulate it, but that is the extent of it.

您提出的API中还存在另一个问题:您将如何制定方法的返回类型? 是一个boost::any类,适合于存储该项目,但是如果您仍然不知道其类型,将无法对其进行任何有用的处理.

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.

这篇关于相当于Python getattr的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆