Note that there are some explanatory texts on larger screens.

plurals
  1. POVector, proxy class and dot operator in C++
    text
    copied!<p>A question related to a custom Vector class in C++.</p> <pre><code>template &lt;typename T&gt; class Vector { ... private: T * mData; int mSize; public: proxy_element operator[](const size_type index) { return proxy_element(*this, index); } const T&amp; operator[](const size_type index) const { return mData[index]; } }; template &lt;typename T&gt; class proxy_element { ... proxy_element(Vector&lt;T&gt;&amp; m_parent, const size_type index); proxy_elem&amp; operator=(const T&amp; rhs); // modifies data so invalidate on other memories bool operator==(const proxy_elem&amp; rhs) // only read, just copy data back. ... } </code></pre> <p>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.</p> <p>This design work well when the element type is primitive. However for more complex element types, there is one issue:</p> <pre><code>struct person{ int age; double salary; }; int main() { Vector&lt;person&gt; v1(10); v[1].age = 10; // gives error as operator[] returns proxy_element for which "." operator has no meaning } </code></pre> <p>AFAIK, the "." operator cannot be overload in C++. One obvious solution is to not use proxy_elem and just return regular reference (T &amp;), assuming that each access is a write access, but that will be inefficient for obvious reasons.</p> <p>Is there any other work around which gives me "." operator working while retaining ability to distinguish between read and write operations?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload