Search code examples
c++templatesattributesdynamic-data

C++: Dynamically access class properties


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.

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;
?>

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.


Solution

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

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

    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.