0

Many libraries provide us getter and setters to access and modify there processed variables. One of the libraries is Boost PropertyTree. I want to wrap getter and setter in boost::property_tree::ptree with operator[].

Source:

class XMLDocument {
    boost::property_tree::ptree ptree_;

public:
    XMLDocument(const std::string &content) {
        std::stringstream ss;
        boost::property_tree::read_xml(ss << content, ptree_);
    }
    template <typename T> T &operator[](const std::string &path) { /* TODO */ }
}

int main() {
    XMLDocument xml("<foo>bar</foo><baz>qux</baz>");
    std::cout << xml["foo"] << std::endl; // Access the element.
    xml["baz"] = "quux"; // Modify the element.
    std::cout << xml["baz"] << std::endl;
}

Output:

bar
quux

How can I do?

LeeGom
  • 201
  • 3
  • 10
  • Just to be clear, this is demonstrative code, not compilable code ? – Quentin Aug 03 '15 at 08:43
  • Your code relies on runtime info to give compile-time types. `template`s are not an option when you rely on runtime info. – RamblingMad Aug 03 '15 at 09:16
  • @Quentin Yes. I didn't check whether the code throws syntax errors or not. – LeeGom Aug 03 '15 at 19:31
  • @CoffeeandCode Hmm... Then, should I use `boost::any`s instead of it? – LeeGom Aug 03 '15 at 19:38
  • If you know all of the possible data you might get, just use some sort of polymorphism and throw some error if you get unexpected data. `boost::any` is more of a last resort. – RamblingMad Aug 04 '15 at 02:36

0 Answers0