Search code examples
c++templatesstructoperator-overloadingdynamic-data

C++ [] mapping, possibly through templates


I have a little problem in C++ I don't know how to solve. The first part of the problem is to access an element in a struct via [], or better, to map [] to a subelement.

My struct looks like this:

struct e {
    std::string content;
    std::string name;
    std::map<std::string, std::vector<e> > elements;
};

If I want to access a subelement of e, I can do this like this: e.elements["e1"][0].elements["e1sub"][0].content, would it be possible to map this so I can call it like this: e["e1"][0]["e1sub"][0], this would just mean that he has to "replace" every e[] with e.elements[].

Maybe this can be done with templates but I don't know how to use them yet as I'm just beginning to learn C++.

Thanks in advance for any help, Robin.


Solution

  • You need to overload operator[]. Typically, you want to implement two versions of that operator, but since std::map only overloads the non-const version, that might be enough for you.

    Something like the following should do:

    struct e {
        std::string content;
        std::string name;
        std::map<std::string, std::vector<e> > elements;
    
        std::vector<e>& operator[](const std::string& key) {return elements[key];}
    };