Alex
Alex

Reputation: 163

Passing multiple arguments to operator[]

While I didn't know you cannot overload operator[] in C++ to accept more than one argument, I have accidentally came across the statement that appeared to be valid to my surprise:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> numbers{1, 2, 3, 4};

    int i = 0;
    std::cout << numbers[i++,i+=1,i=1,i+1] << std::endl;
    return 0;
}

So could anyone please explain if there is any benefit of passing multiple expressions to operator[] ?

compiled with mingw g++ 4.8.1 with -std=c++11

Upvotes: 1

Views: 431

Answers (4)

Ron
Ron

Reputation: 15501

Apart from possible side effects, there isn't any benefit, as your numbers[i++, i+=1, i=1, i+1] expression evaluates to numbers[i+1] which is equal to numbers[2] because of how things work when using the comma operator. We can argue this is confusing, hard to read and is of no benefit.

Upvotes: 1

Loop
Loop

Reputation: 237

This is something that might work in interpreted languages like Python, but not in C++.

In this case you have to chain them with the numbers in front

...<<numbers[i-1]<<number[i]<<...

Try to base your design around this limitation.

Upvotes: 0

P.W
P.W

Reputation: 26800

In C++, comma works both as a separator and an operator. In this particular case, it works as an operator.

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing) (until C++17).

The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand, E2. If E2 is a temporary expression (since C++17), the result of the expression is that temporary expression (since C++17). If E2 is a bit-field, the result is a bit-field.

So

numbers[i++,i+=1,i=1,i+1];

becomes

numbers[i+1];

Upvotes: 1

lubgr
lubgr

Reputation: 38267

You are not passing multiple arguments to an overloaded operator, but instead you use the comma operator for evaluating a single function parameter. There is no benefit associated with it, except confusing co-workers you dislike. The statement

numbers[i++,i+=1,i=1,i+1]

evaluates i++, then i += 1, then i = 1, then i + 1 and returns the last evaluated expression, which is 2.

While there are valid use cases for the comma operator, this is not one of them.

Upvotes: 5

Related Questions