简体   繁体   English

这是逗号运算符的可接受用法吗?

[英]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. 我在Stack Overflow上看到了其他帖子,它们极力阻止逗号运算符的重载。 I was sent a Github pull request with a comma operator overload which looked something like the following: 我发送了一个带有逗号运算符重载的Github pull请求,看起来如下所示:

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? 有人可以解释为什么这是一个好的或坏的用例?

使用<<会更有意义,逗号通常不意味着流操作并且会导致令人困惑的代码

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. 但是,如果在哪里创建一个Mylogger对象,那么重载的运算符会混淆并导致各种麻烦。

So, at the very least, if Mylogger was an implementation detail then it may be a valid use case. 所以,至少,如果Mylogger是一个实现细节,那么它可能是一个有效的用例。 Now in C++11 with variadic function templates there is no need to resort to this kind of twisted code. 现在在带有可变参数函数模板的 C ++ 11中 ,没有必要求助于这种扭曲的代码。

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. 最近,我已成为Google风格指南的粉丝,它不是任何运营商重载的忠实粉丝。 They have some really good reasons you can learn about here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading 他们有一些很好的理由可以在这里了解: http//google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Operator_Overloading

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM