3 ms·
C++ allows overloading the comma operator. This can be (ab)used to make the following syntax work for, e.g., initializing a vectorish type: MyType obj = 1,
by bobbyi 15y ago
C++ allows overloading the comma operator. This can be (ab)used to make the following syntax work for, e.g., initializing a vectorish type:
MyType obj = 1, 2, 3;
Due to the precedence of operators, this is actually equivalent to
((MyType obj = 1), 2), 3;
so as long as the overloaded assignment operator returns an object that the comma operator mutates and returns, this can be made the have effect of initializing the declared object to a "list".
This trick is used by Boost Spirit to allow things like (example from http://stackoverflow.com/questions/54142/c-comma-operator http://stackoverflow.com/questions/54142/c-comma-operator)
keywords = "and", "or", "not", "xor";
- jerryr 15y agoI think that when you overload the comma operator in C++, you change the nature of the sequence point. I believe you're no longer guaranteed to have "1, 2, 3" evaluated in that order. In your example, this doesn't matter, but if it was "f1(), f2(), f3()" and for some reason the sequence of those calls determined what each returned, you might have a problem. I could be wrong here though--my C++ is rusty from years of disuse.
- bobbyi 15y agoItem #7 in More Effective C++ is to "never overload &&, || or ," because it changes the order of evaluation (with the boolean logic operators, it changes because the usual short-circuiting behavior is gone since the second argument has to be evaluated to pass it as an argument).