Overload operator[] with different return Type

Viewed 71

I am working on JSON format using <C++98> and for that reason, I have defined 3 classes :

class Json {
public:
    string key;
};
class JsonElement:public Json {
public:
    string value;
}
class JsonObject: public Json {
public:
    std::vector<Json*> elements;

I neglected the JsonList for the moment.

I overloaded the operator[] so that if the operator finds another JsonObject, it will call the operator[] once again until it finds JsonElement and here it returns the value and not a Json

I don't know if I can use enable_if to achieve that or maybe you have another solution.

the idea is this : (this is not a code just the idea)

Json || string operator[](const char* key){
     
     if(this->getElementByKey(key) is JsonObject)
         return Json;
     else if(this->getElementByKey(key) is JsonElement)) 
         return this->getElementByKey(key)->value;
}

in that way we can use for example :

JsonObject jObj;

string value = jObj["key1"]["key2"]

0 Answers
Related