矢量,代理类和点运算符在C + + [英] Vector, proxy class and dot operator in C++

查看:132
本文介绍了矢量,代理类和点运算符在C + +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与C ++中的自定义Vector类相关的问题。

A question related to a custom Vector class in C++.

template <typename T>
class Vector
{ ...
  private:
    T * mData; int mSize;
  public:
    proxy_element operator[](const size_type index) { return proxy_element(*this, index); }
    const T& operator[](const size_type index) const {   return mData[index]; }
};

template <typename T>
class proxy_element
{  ...
   proxy_element(Vector<T>& m_parent, const size_type index);
   proxy_elem& operator=(const T& rhs); // modifies data so invalidate on other memories
   bool operator==(const proxy_elem& rhs) // only read, just copy data back.
   ...
}

使用proxy_element类的原因是并且优化读取和写入操作,考虑矢量数据也可以驻留在GPU设备存储器中。因此,任何读取操作只需要将最新数据复制回来(如果有的话),但是读/写操作要求设备存储器中的数据无效。

The reason for using proxy_element class is to distinguish and optimize read and writes operations, considering that the vector data can reside in GPU device memories as well. So any read operation require only to copy latest data back (if any) but a readwrite/write operation require invalidating data in device memories.

类型是原始的。但对于更复杂的元素类型,有一个问题:

This design work well when the element type is primitive. However for more complex element types, there is one issue:

struct person{ int age; double salary; }; 
int main()
{
   Vector<person> v1(10); 
   v[1].age = 10; // gives error as operator[] returns proxy_element for which "." operator has no meaning
}

AFAIK,。运算符不能在C ++中重载。一个明显的解决方案是不使用proxy_elem,只是返回正常引用(T&),假设每个访问都是写访问,但是由于显而易见的原因,这将是无效的。

AFAIK, the "." operator cannot be overload in C++. One obvious solution is to not use proxy_elem and just return regular reference (T &), assuming that each access is a write access, but that will be inefficient for obvious reasons.

有任何其他工作给我。

Is there any other work around which gives me "." operator working while retaining ability to distinguish between read and write operations?

推荐答案

一个选择是使这些数据类型不可变(private member)变量,由构造函数初始化,唯一的setter是类的赋值运算符)。这样,改变任何东西的唯一方法是分配给整个类的实例,可以通过proxy_element来引导。

One option is to make such data types immutable (private member variables, initialised by a constructor, and the only setter is the class's assignment operator). This way, the only means to change anything is to assign to an entire instance of the class, which can be channeled through a proxy_element.

这篇关于矢量,代理类和点运算符在C + +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆