AC.
AC.

Reputation: 1003

Is this an acceptable use of the comma operator?

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?

Upvotes: 6

Views: 175

Answers (3)

It&#39;sPete
It&#39;sPete

Reputation: 5211

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

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

Upvotes: 0

K-ballo
K-ballo

Reputation: 81349

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.

Upvotes: 4

Ofir
Ofir

Reputation: 8362

It would make much more sense to use <<, the comma doesn't usually mean a stream operation and would result in confusing code

Upvotes: 6

Related Questions