Search code examples
c++operator-overloadingsubscript-operator

Overload the subscript operator to call a function based on the type assigned


I have an object that has functions like addString and addInteger. These functions add data to a JSON string. At the end, the JSON string can be obtained and sent out. How can this be made easier by overloading subscript operators to do the following?

jsonBuilder builder();

builder[ "string_value" ] = "Hello";
builder[ "int_value" ] = 5;
builder[ "another_string" ] = "Thank you";

Solution

  • You need to have a proxy class that is returned by the operator[] function and which handles the assignment. The proxy class then overloads the assignment operator to handle strings and integers differently.

    Something like this:

    #include <iostream>
    #include <string>
    
    struct TheMainClass
    {
        struct AssignmentProxy
        {
            std::string name;
            TheMainClass* main;
    
            AssignmentProxy(std::string const& n, TheMainClass* m)
                : name(n), main(m)
            {}
    
            TheMainClass& operator=(std::string const& s)
            {
                main->addString(name, s);
                return *main;
            }
    
            TheMainClass& operator=(int i)
            {
                main->addInteger(name, i);
                return *main;
            }
        };
    
        AssignmentProxy operator[](std::string const& name)
        {
            return AssignmentProxy(name, this);
        }
    
        void addString(std::string const& name, std::string const& str)
        {
            std::cout << "Adding string " << name << " with value \"" << str << "\"\n";
        }
    
        void addInteger(std::string const& name, int i)
        {
            std::cout << "Adding integer " << name << " with value " << i << "\n";
        }
    };
    
    int main(int argc __attribute__((unused)), char *argv[] __attribute__((unused)))
    {
        TheMainClass builder;
        builder[ "string_value" ] = "Hello";
        builder[ "int_value" ] = 5;
        builder[ "another_string" ] = "Thank you";
    }
    

    See here for a working example.