I'm looking for a way to prevent ++x++
from working for types with user defined prefix and postfix increment operators.
For builtin types the result type of the postfix operator is not an lvalue but a prvalue expression and the compilers complain nicely.
The simplest thing i can think of is to return const for the postfix increment operator:
struct S {
int i_;
S& operator++() {
++i_;
return *this;
}
S /*const*/ operator++(int) {
S result(*this);
++(*this);
return result;
}
};
int main() {
S s2{0};
++s2++;
}
Is this approach flawed?
Edit:
Thanks to the answers, i found more information here, here and of course on cppreference.
You probably want S& operator++() &
and S operator++(int) &
. You're missing the &
at the end that makes the operators only work on lvalues.