运算符重载 C++:只写版本

2024-02-03

我正在重载数据结构的运算符,因此我有标准函数声明:

T & operator[](int i);    //used for regular objects
const T & operator[](int i) const;  // used for const objects

所以我想做的是为常规对象提供两个版本的operator[]:当operator[]用于写入而不是读取时,一个版本会执行不同的操作。

我一直在读到这是可能的,但我还没有看到任何代码。

我已经多次看到这个问题被问到,并且我看到了答案“'operator[] const'版本用于读取”-->但这不是真的;它仅与类的 const 实例一起使用。

任何人都可以提供有关检测写入事件以触发不同行为的指导吗? 也许是复制构造函数中的技巧?


持有对象的类无法获取您对返回对象的访问是读还是写访问的信息。

只有对象本身通过成员函数限定符才具有“我在哪个上下文中使用”的概念。

  • 参考限定符
  • const/易失性限定符

您可以在代理类中使用它。

#include <vector>
#include <type_traits>
#include <iostream>

template <class T, class U = T, bool Constant = std::is_const<T>::value>
class myproxy
{
protected:
  U& m_val;
  myproxy& operator=(myproxy const&) = delete;
public:
  myproxy(U & value) : m_val(value) { }
  operator T & ()
  {
    std::cout << "Reading." << std::endl;
    return m_val;
  }
};

template <class T>
struct myproxy < T, T, false > : public myproxy<T const, T>
{
  typedef  myproxy<T const, T> base_t;
public:
  myproxy(T & value) : base_t(value) { }
  myproxy& operator= (T const &rhs)
  {
    std::cout << "Writing." << std::endl;
    this->m_val = rhs;
    return *this;
  }
};

template<class T>
struct mycontainer
{
  std::vector<T> my_v;
  myproxy<T> operator[] (typename std::vector<T>::size_type const i)
  {
    return myproxy<T>(my_v[i]);
  }
  myproxy<T const> operator[] (typename std::vector<T>::size_type const i) const
  {
    return myproxy<T const>(my_v[i]);
  }
};

int main()
{
  mycontainer<double> test;
  mycontainer<double> const & test2(test);
  test.my_v.push_back(1.0);
  test.my_v.push_back(2.0);
  // possible, handled by "operator=" of proxy
  test[0] = 2.0;
  // possible, handled by "operator T const& ()" of proxy
  double x = test2[0];
  // Possible, handled by "operator=" of proxy
  test[0] = test2[1];
}

Prints


Writing
Reading
Reading
Writing  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

运算符重载 C++:只写版本 的相关文章

随机推荐