Is this an acceptable use of the comma operator?

I saw other stack overflow messages that strongly prevent the operator from overloading the comma. I was sent a request to migrate Github with an overload of the comma operator, which looked something like this:

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 use case?

+6
source share
3 answers

This is subjective, but I would say that this is not a very good use case, because it conveys incorrect semantics. There is already an operator used for output, << will be the best choice.

The code uses variable macros along with an overloaded comma operator, which is smart and can be good for a particular situation. However, if you create a Mylogger object, the overloaded operator will confuse and cause all kinds of problems.

So, at least if Mylogger was an implementation detail, this might be a valid use case. Now in C ++ 11 with templates of variational functions there is no need to resort to such virtualized code.

+4
source

It would be wiser to use <<, a comma usually does not mean a stream operation and will lead to code obfuscation

+6
source

Operator overloading should only be done when use is extremely transparent to the caller / user of your class. If in doubt, just create a method that does what you want and name it according to good naming conventions. Usually there is no standard use for a comma, so adding a comma operator will have a user of your class scratching his / her head.

Recently, I have become a fan of the Google style guide, which is not a big fan of ANY operator overload. They have some really good reasons you can learn about here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading

0
source

All Articles