C ++:动态访问类属性 [英] C++: Dynamically access class properties

查看:135
本文介绍了C ++:动态访问类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能访问类的属性动态地不知道在运行时访问的属性的名称。

I'm wondering if it is possible to access a property of a class dynamically without knowing the name of the property accessed at run-time.

为了让大家更好地了解什么,我瞄准的,这个PHP code应证明什么,我想做的事:

To give you a better understanding of what I'm aiming at, this php code should demonstrate what I want to do:

<?php
$object = new object();
$property = get_name_out_of_textfile();
echo $object->$property;
?>

我知道这是不可能的做同样的事情,但让我们说我有性病::字符串的CString的属性的名称和要访问匹配名称的属性。有没有办法做到这一点?

I know that is it not possible to do the exact same thing but let's say I got the name of an attribute in a cstring of std::string and want to access the attribute matching the name. Is there a way to do that?

的背景是,我想动态加载和从一个类保存数据,有很多属性。我可以保存在我想要的任何格式,但我需要一个方式来加载它们放回无需再次每次都指定确切的属性。

The background is that I want to dynamically load and save data from a class with lots of attributes. I can save the in any format I want but I need a way to load them back in again without specifying the exact attribute every time.

在此先感谢您的帮助,
罗宾。

Thanks in advance for any help, Robin.

推荐答案

基本上,你需要创建一个额外的功能,ALA:

Basically, you need to create an extra function, ala:

std::string get(const std::string& field, const std::string& value_representation)
{
    std::ostringstream oss;
    if (field == "a")
        oss << a;
    else if (field == "b")
        oss << b;
    else
        throw Not_Happy("whada ya want");
    return oss.str();
}

有很多现有框架的要做到这一点,诸如升压序列库。其中大部分涉及使用某种标记,或更糟的声明你的类 - 离域二次元

There are lots of existing frameworks to do this, such as the boost serialization library. Most involve declaring your class using some kind of markup, or worse - delocalised secondary metadata.

如果你真的需要创伤小东西,那么工具,如GCC-XML和OpenC的++允许您自动化这些功能的代(前者可以很容易地与XML库,一点点Python或Ruby,合并在一个很容易,但低性能的胜利)。

If you really need something less invasive, then tools such as Gcc-XML and OpenC++ allow you to automate the generation of these functions (the former can easily be combined with XML libraries, a little python or ruby, for an easy but low performance win).

只是要绝对清楚,C ++不提供任何自动化的,符合标准的方式来做到这一点。没有流行的编译器提供此扩展。在desparation,你可以得到的地方解析自己的调试信息,但是这绝对不推荐。

Just to be absolutely clear, C++ does not provide any automated, Standard-compliant way to do this. No popular compilers provide extensions for this. In desparation, you may be able to get somewhere parsing your own debug information, but that's definitely not recommended.

这篇关于C ++:动态访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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