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

Overloading subscript operators for specific read and write operations

本文关键字:重载 下标 运算符 操作 读写      更新时间:2023-10-16

我当前正试图为读取和写入操作重载"[]"运算符。我创建了它们,如下所示:

V operator[] (K key) const; //Read
V& operator[] (K key);      //Write

然而,只有"写入"从以下两个调用:

foo["test"] = "bar"; //Correct, will use 'write'
cout << foo["test"]; //Incorrect, will use 'write'

造成这种情况的原因是什么?有可能的解决方案吗?

同样的问题没有帮助,可以在这里找到:C++:重载[ ;] ;读写访问的操作员

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

重载是基于参数的静态类型完成的。如果使用运算符的对象foo是非const,则使用非const重载。如果是const,则使用const过载。

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

 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); }
     // ...
 };