I'm struggling with the design of a few (probably two) C++ classes that work together and implement sort of a data container (Vector) and a data wrapper (Integer) that wraps individual vector elements (or better to say the access to it). The Vector simply holds a vector of int. The Integer/wrapper provides access to an int (possibly without holding it).
Requirements:
- Wrapper/Integer must be available as lvalue
- The data container should hold the data as an vector of
int(not as a vector of Integer) - The wrapper also holds some other data members (no reinterpreting cast
int-> Integer possible)
I fail to design this (see below) without running into the problem where an lvalue reference cannot bind to a temporary. I understand that that's not possible and I understand that code is wrong (and why it's wrong). There's no need to explain that lvalue references can't bind to rvalues. I'm struggling to find a solution to above requirements without this problem.
How to design this in C++? (Can be any modern standard)
#include<vector> class Integer { int& ref_t; bool other_data_member; public: Integer(int& rhs): ref_t(rhs) {} Integer& operator=( int i ) { ref_t = i; return *this; } }; class Vector { std::vector<int> data; public: Vector(): data(10) {} Integer& operator[](int i) { return Integer( data[i] ); // caution: this doesn't work } }; void write_one( Integer& i ) { i = 1; } int main() { Vector v; write_one( v[5] ); } https://stackoverflow.com/questions/67215461/design-to-avoid-binding-lvalue-reference-to-temporary-for-data-container-and-wra April 22, 2021 at 10:40PM
没有评论:
发表评论