gpt4 book ai didi

c++ - C++17 中的折叠表达式 - 比较运算符的用例

转载 作者:IT老高 更新时间:2023-10-28 22:39:44 25 4
gpt4 key购买 nike

根据N4295 C++17 将允许我计算未知数量的参数的总和:

template<typename ... T>
int sum(T...t)
{
return (... + t);
}

该文档进一步指出,我可以使用 == 或 > 等运算符来代替 +。任何人都可以想出一个明智的例子来说明我什么时候想在这样的结构中使用 == 或 >?

(我意识到人们可以定义 == 和 > 来对奇怪的类做奇怪的事情,但这肯定违反了良好的做法。编写 a > b > c > d 几乎不是一个好主意,是吗?)

最佳答案

如果像在 Python 中那样处理链式比较,我将是一个有趣的功能,其中 a < b < c被解释为 a < b and b < c单次评估 b .不幸的是,在 C++ 中情况并非如此,即使在奇怪的情况下,折叠比较运算符确实没有意义。

请注意,有 a proposal (P0313) 实际删除运算符 == , != , < , > , <=>=完全来自折叠表达式处理的运算符。 2016 年 6 月在奥卢召开的委员会 session 上对此进行了讨论。删除的动机相当简短:

Comparison operators don't make much sense in fold-expressions; they expand into expressions that have surprising effects, and are thus useful for dsl-metaprogrammers only. [...] It would be nice to be able to fix expressions like a < b < c. That would require a time machine. Not repeating the problem for fold-expressions seems doable.

也就是说提案被拒绝了。

关于c++ - C++17 中的折叠表达式 - 比较运算符的用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37361286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com