MACE  1.0.0
 All Classes Namespaces Files Functions Variables Enumerations Defines
Generics
Reflect Library

Dynamic runtime access to fields of reflected classes. More...

Given a reflected type, mace::reflect::value, mace::reflect::value_ref, and mace::reflect::value_cref provide dynamic runtime querying of the members on the type. This is an ideal replacement for void* or even boost::any.

struct contact {
    contact( const std::string& f, const std::string& l, int z )
    :first_name(f),last_name(l),zip(z){}

    std::string first_name;
    std::string last_name;
    int         zip;
};

struct address_book {
    std::string name;
    bool        is_locked;
    std::vector<contact> contacts;
};

MACE_REFLECT( contact, (first_name)(last_name)(zip) )
MACE_REFLECT( address_book, (name)(is_locked)(contacts) )
    address_book ab;  
    ab.name      = "My Address Book";
    ab.is_locked = false;
    ab.contacts.push_back( contact( "Steve", "Jobs", 90210 ) );
    ab.contacts.push_back( contact( "Bill", "Gates", 10000 ) );

    // store a generic reference to the address book
    reflect::value_ref v(ab);

    // access sub members
    ab["is_locked"].as<int>();  // 0
    ab["is_locked"].as<std::string>(); // "false"
    ab["is_locked"].as<address_book>(); // throws bad_value_cast

    // store a generic const reference to the address book
    reflect::value_cref cv(ab);

    // create a copy of ab, like boost::any, except you can still query and access methods.
    reflect::value cv(ab);

    std::cerr<< v["contacts"][0]["first_name"].as<std::string>() <<std::endl; // print Steve
    v["contacts"][0]["first_name"].set_as( std::string( "New Name" ) );

    BOOST_ASSERT( ab.contacts[0].first_name == "New Name" );

You can use convert a reflect::value to json with the following code: