重载特定读写操作的下标运算符

one*_*dan 3 c++ overloading subscript

我目前正在尝试为读取和写入操作重载“[]”运算符。我创建了它们,如下所示:

V operator[] (K key) const; //Read
V& operator[] (K key);      //Write
Run Code Online (Sandbox Code Playgroud)

但是,仅从以下两个调用“写入”:

foo["test"] = "bar"; //Correct, will use 'write'
cout << foo["test"]; //Incorrect, will use 'write'
Run Code Online (Sandbox Code Playgroud)

这是什么原因,是否有可能的解决方案?

同样没有帮助的问题,在这里找到:C++: Overloading the [ ] operator for read and write access

尽管如此,所提供的解决方案并未按预期工作,并且仍然只访问了写重载。

Die*_*ühl 5

重载是根据参数的静态类型完成的。如果foo您使用运算符的对象是非constconst则使用非重载。如果是constconst则使用过载。

如果你想区分读和写,你需要从你的下标运算符返回一个代理,它转换为适合阅读的类型,并有一个适合写作的赋值运算符:

 class X;
 class Proxy {
     X*  object;
     Key key;
 public:
     Proxy(X* object, Key key): object(object), key(key) {}
     operator V() const { return object->read(key); }
     void operator=(V const& v) { object->write(key, v); }
 };
 class X {
     // ...
 public:
     V    read(key) const;
     void write(key, V const& v);
     Proxy operator[](Key key)       { return Proxy(this, key); }
     V     operator[](Key key) const { return this->read(key); }
     // ...
 };
Run Code Online (Sandbox Code Playgroud)