重载下标运算符以根据分配的类型调用函数

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

我有一个对象具有 addStringaddInteger 等功能。这些函数将数据添加到 JSON 字符串。最后可以获取到JSON字符串发送出去。如何通过重载下标运算符来执行以下操作使这更容易?

jsonBuilder builder();

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

您需要有一个 proxy class,它由 operator[] 函数返回并处理分配。代理 class 然后重载赋值运算符以不同方式处理字符串和整数。

像这样:

#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.

我想你终于需要这个了。我已经实现了获取字符串输入,对整数执行相同的操作。

#include <iostream>
#include <string>
#include <map>

class jsonBuilder
{
    public:
        std::map<std::string,std::string> json_container;
        std::string&  operator[](char *inp)
        {
            std::string value;
            json_container[std::string(inp)];
            std::map<std::string,std::string>::iterator iter=json_container.find(std::string(inp));

            return iter->second;            
        }   
};

int main()
{
    jsonBuilder jb;
    jb["a"]="b";

    std::map<std::string,std::string>::iterator iter=jb.json_container.find(std::string("a"));
    std::cout<<"output: "<<iter->second;
}