6

Looking at std::for_each_n's possible implementation:

template<class InputIt, class Size, class UnaryFunction>
InputIt for_each_n(InputIt first, Size n, UnaryFunction f)
{
    for (Size i = 0; i < n; ++first, (void) ++i) {
        f(*first);
    }
    return first;
}

I noticed that the part where we typically see i++ (or, the preferred ++i) consists of two operations:

  • ++first
  • (void) ++i

separated by a comma. While most of it makes sense, the (void) cast seems a little surprising to me. All I can guess is that there could be an overloaded operator , that takes the deduced type of InputIt and Size which would result in some surprising side-effects. Could that be the reason? If yes, are we sure that cast to void solves that issue entirely?

Boann
  • 48,794
  • 16
  • 117
  • 146
Fureeish
  • 12,533
  • 4
  • 32
  • 62
  • 1
    related/good read: https://stackoverflow.com/questions/39514765/the-void-the-comma-operator-operator-and-the-impossible-overloading – NathanOliver Feb 18 '20 at 13:32
  • 1
    Does this answer your question? [The void(), the comma operator (operator,) and the impossible (?) overloading](https://stackoverflow.com/questions/39514765/the-void-the-comma-operator-operator-and-the-impossible-overloading) – Xatyrian Feb 18 '20 at 13:51

1 Answers1

4

Could that be the reason?

Handling the evil overload of operator comma is indeed a good reason.

I don't see other (valid) reasons.

If yes, are we sure that cast to void solves that issue entirely?

Yes, we cannot overload operator comma with void (neither with conversion to void).

Jarod42
  • 203,559
  • 14
  • 181
  • 302