C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Should postfix increment and decrement operators be automatically obtainable from their prefix versions?

From: Matthew Taylor <mjtaylor214_at_[hidden]>
Date: Wed, 24 Jan 2024 15:50:07 +0000
I did see that paper, but it took a different approach from my proposed one. P1046 suggested automatically generating both operator++ overloads in terms of an addition operator as equivalent to foo += 1. Personally that would not be my preferred approach as in my view incrementing something that does not model an integer is not necessarily equivalent to adding an integer value of 1 to it; and we already have several types in C++ which have well defined increment and decrement operators but no addition operators to prove it. My approach is much simpler and starts from a much less broad position - that in almost all cases if the user defines a prefix operator then they probably want a postfix operator which behaves following the same pattern that postfix operators behave for builtins.

> You'd have to make a very strong case for hardcoding a specific implementation in the core language instead of letting the user decide.

On this, I do apologise if I wasn't clear, but my intention is in no way to forbid the user from being able to define the operators how they please. They are still perfectly able to define prefix and postfix operators in exactly the way they are now. However, if they are in the common situation where they want to do as the ints do, writing out two functions for one conceptual operation is just boilerplate that nobody enjoys.

I'd say it mirrors that changes to the equality operators in C++20. In current C++, should you decide to define operator== for your class (or of course operator<=>) then you automatically get an implicitly-generated operator!= which returns the negation of the result of operator== for those types. As a code author you are still perfectly able to define your own operator!= to do what you desire (even if it breaks with the traditional meaning of == and !=), but in the overwhelming majority of cases you want your operator!=(foo lhs, foo rhs) to return the equivalent of !(lhs == rhs) anyway, and the implicitly generated functions save you that boilerplate and possibility of making a mistake.

Received on 2024-01-24 15:50:13