I've seen other posts on Stack Overflow which highly discourage overloading of the comma operator. I was sent a Github pull request with a comma operator overload which looked something like the following:
class Mylogger {
public:
template <typename T>
Mylogger & operator,(const T & val) {
std::cout << val;
return * this;
}
};
#define Log(level,args...) \
do { Mylogger logv; logv,level, ":", ##args; } while (0)
Then you can use it as follows:
Log(2, "INFO: setting variable \", 1, "\"\n");
Can someone explain why this is a good or bad usage case?
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
JavaScript uses a comma ( , ) to represent the comma operator. A comma operator takes two expressions, evaluates them from left to right, and returns the value of the right expression. In this example, the 10, 10+20 returns the value of the right expression, which is 10+20. Therefore, the result value is 30.
In C++, we can overload the comma operator using Operator Overloading. For Example: For “Send the query X to the server Y and put the result in variable Z”, the “and” plays the role of the comma. The comma operator (, ) is used to isolate two or more expressions that are included where only one expression is expected.
It would make much more sense to use <<, the comma doesn't usually mean a stream operation and would result in confusing code
That's subjective, but I would say it isn't a good usage case because it conveys the wrong semantics. There is already an operator used for output, <<
would be a better choice.
The code is taking advantage of variadic macros together with overloaded comma operator, which is clever and may be fine for that particular situation. However, if one where to create a Mylogger
object then the overloaded operator would be confusing and cause all sort of troubles.
So, at the very least, if Mylogger
was an implementation detail then it may be a valid use case. Now in C++11 with variadic function templates there is no need to resort to this kind of twisted code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With