問題描述
我經(jīng)常看到關(guān)于在 C++ 中重載逗號(hào)運(yùn)算符的問題(主要與重載本身無關(guān),但與序列點(diǎn)的概念有關(guān)),這讓我感到疑惑:
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:
什么時(shí)候應(yīng)該重載逗號(hào)?它的實(shí)際用途有哪些例子?
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;
在現(xiàn)實(shí)世界的代碼中,所以我很好奇何時(shí)(如果有的話)實(shí)際使用它.
in real-world code, so I'm curious as to when (if ever) this is actually used.
推薦答案
讓我們稍微改變一下重點(diǎn):
Let's change the emphasis a bit to:
什么時(shí)候你應(yīng)該重載逗號(hào)?
When should you overload the comma?
答案:從不.
例外:如果你在做模板元編程,operator,
在運(yùn)算符優(yōu)先級(jí)列表的最底部有一個(gè)特殊的位置,它可以派上用場(chǎng),用于構(gòu)建 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,
的僅有的兩個(gè)實(shí)際用途都在 Boost:
The only two practical uses I've seen of overloading operator,
are both in Boost:
- Boost.Assign
- Boost.Phoenix這里的基礎(chǔ)在于它允許 Phoenix lambdas 支持多個(gè)語句
- Boost.Assign
- Boost.Phoenix – it's fundamental here in that it allows Phoenix lambdas to support multiple statements
這篇關(guān)于什么時(shí)候重載逗號(hào)運(yùn)算符?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!