什么时候重载逗号运算符?

2021-12-07 00:00:00 function operator-overloading c++

我经常看到关于在 C++ 中重载逗号运算符的问题(主要与重载本身无关,但与序列点的概念有关),这让我感到疑惑:

I see questions on SO every so often about overloading the comma operator in C++ (mainly unrelated to the overloading itself, but things like the notion of sequence points), and it makes me wonder:

什么时候应该重载逗号?它的实际用途有哪些例子?

When should you overload the comma? What are some examples of its practical uses?

我只是想不出任何我见过或需要的例子

I just can't think of any examples off the top of my head where I've seen or needed to something like

foo, bar;

在现实世界的代码中,所以我很好奇何时(如果有的话)实际使用它.

in real-world code, so I'm curious as to when (if ever) this is actually used.

推荐答案

让我们稍微改变一下重点:

Let's change the emphasis a bit to:

什么时候你应该重载逗号?

When should you overload the comma?

答案:从不.

例外:如果你在做模板元编程,operator, 在运算符优先级列表的最底部有一个特殊的位置,它可以派上用场,用于构建 SFINAE-guards 等.

The exception: If you're doing template metaprogramming, operator, has a special place at the very bottom of the operator precedence list, which can come in handy for constructing SFINAE-guards, etc.

我见过的重载 operator, 的仅有的两个实际用途都在 Boost:

The only two practical uses I've seen of overloading operator, are both in Boost:

  • Boost.Assign
  • Boost.Phoenix这里的基础在于它允许 Phoenix lambdas 支持多个语句
  • Boost.Assign
  • Boost.Phoenix – it's fundamental here in that it allows Phoenix lambdas to support multiple statements

相关文章