Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cast the result of pre-incrementation to void in comma separator context? [duplicate]

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?

like image 728
Fureeish Avatar asked Feb 18 '20 13:02

Fureeish


1 Answers

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).

like image 50
Jarod42 Avatar answered Nov 13 '22 08:11

Jarod42