I want to write class similar to below, where IteratorLike
can only be dereferenced to a new value, as the iterator provides a view different to the underlying structure that makes returning a simple reference unfeasible.
class IteratorLike
{
public:
MyValue operator*() const { return MyValue(...); }
auto operator->() const { return **this; } // This does not work generally due to member access semantics.
};
All in all, I just want IteratorLike()->x
to mean the same thing as (*IteratorLike()).x
.
One could simply overload operator->()
in the MyValue
class, but i want this to work in all cases.
Using a wrapper type that overloads operator->()
seemed like a plausible solution, but this does not work when returning an rvalue.
In the example on godbolt is a working implementation of such a wrapper, including the undefined behaviour it causes due to the dangling reference.
If the wrapper could return a pointer to an prvalue, then the line int &qa = MyIteratorLike()->x;
would in my understanding be caught by the compiler, but such a thing seems impossible.
Is there a way to make this work?
No. Value category is a property of an expression, not of a type. "pointer to prvalue" is not a thing