gpt4 book ai didi

c++ - 为什么 C++20 范围库有自己的命名空间?

转载 作者:行者123 更新时间:2023-12-03 06:49:42 24 4
gpt4 key购买 nike

为什么是 std::range::sort (和其他基于范围的算法)在 range 中实现命名空间?为什么不定义为 std::sort 的重载取一个范围?

最佳答案

这是为了避免破坏现有的代码库。 Eric Niebler、Sean Parent 和 Andrew Sutton 在他们的设计论文 D4128 中讨论了不同的方法。 .

3.3.6 Algorithm Return Types are Changed to Accommodate Sentinels

... In similar fashion, most algorithm get new return types when theyare generalized to support sentinels. This is a source-breaking changein many cases. In some cases, like for_each, the change is unlikely tobe very disruptive. In other cases it may be more so. Merely acceptingthe breakage is clearly not acceptable. We can imagine three ways tomitigate the problem:

  1. Only change the return type when the types of the iterator and the sentinel differ. This leads to a slightly more complicated interfacethat may confuse users. It also greatly complicates generic code,which would need metaprogramming logic just to use the result ofcalling some algorithms. For this reason, this possibility is notexplored here.

  2. Make the new return type of the algorithms implicitly convertible to the old return type. Consider copy, which currently returns theending position of the output iterator. When changed to accommodatesentinels, the return type would be changed to something like pair<I, O>; that is, a pair of the input and output iterators. Instead ofreturning a pair, we could return a kind of pair that is implicitlyconvertible to its second argument. This avoids breakage in some, butnot all, scenarios. This subterfuge is unlikely to go completelyunnoticed.

  3. Deliver the new standard library in a separate namespace that users must opt into. In that case, no code is broken until the userexplicitly ports their code. The user would have to accommodate thechanged return types then. An automated upgrade tool similar to clangmodernize can greatly help here.

We, the authors, prefer (3).


最终,它对使用支持 C++20 的编译器进行构建的现有代码库的破坏最小。这是他们自己喜欢的方法,其余的似乎都是历史。

关于c++ - 为什么 C++20 范围库有自己的命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64518019/

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