3 ms·
> Overloading the Comma Operator Is Powerful Clearly, it's over 9000! ... more seriously though, overloading the comma operator is a bad idea and you shouldn'
by einpoklum 6y ago
> Overloading the Comma Operator Is Powerful
Clearly, it's over 9000!
... more seriously though, overloading the comma operator is a bad idea and you shouldn't do it. In fact, almost nobody does it.
Specifically, you don't want to break the principle of least astonishment with a command such as
v+= 1,2,3,4,5;
Assuming you want to add up a bunch of literals, what you could do is something like:
std::array data { 1,2,3,4,5 };
v += std::reduce(data.begin(), data.end());
and if you've implemented some <algorithm> and <numeric> wrappers for containers, you would have something like an
template<class Container>
typename Container::value_type
reduce(const Container& container);
and then you would write
v += reduce(std::array{ 1,2,3,4,5 } );
which is terse and much clearer.
- jzwinck 6y agoAn even more concise form is built in, and I think more obvious to readers: v.insert(v.end(), { 1, 2, 3, 4, 5 });
- einpoklum 6y agoI was actually not describing adding elements to a container, but adding up values.
- owl57 6y agoSee? That's the problem with arithmetic on containers. Python has that already: v += 4, 5, 6 Comma doesn't do weird shit: that's just a tuple of numbers. But "+=" then does weird shit: it means concatenation when v is a standard library list, and element-wise addition when v is a numpy vector.
- deleted 6y ago[deleted]