c++ - 为什么 std::copy_n 采用模板参数而不是 std::size_t?

标签 c++ c++11

这么简单的问题。

template<class InputIt, class Size, class OutputIt>
OutputIt copy_n(InputIt first, Size count, OutputIt result);

为什么 std::copy_n 为要复制的元素数量取一个类型,而不是简单地 std::size_t?我只是想不出一个理由。

template<class InputIt, class OutputIt>
OutputIt copy_n(InputIt first, std::size_t count, OutputIt result);

最佳答案

在这种情况下,推测原始原理大多是徒劳的,但对于这种设计 copy_n 可以用负计数调用,例如intptrdiff_t type,在这种情况下它什么都不做,标准化委员会的成员肯定很清楚这一点,他们都是非常有能力的人。


另一个优点是对于特殊的迭代器,例如输入和输出迭代器,大小可能大于任何可能的指针差异,因此可能大于 size_t。可以代表。例如。对于 32 位 Windows 中大于 4GB 的文件来说就是如此。 copy_n的定义以明显的指针/迭代器算法表示,“对于每个非负整数 i < n , 执行 *(result + i) = *(first + i) ”,这似乎确实将这种优势归于非常特殊的情况,但该表示法适用于纯输入和输出迭代器,如

中所述 C++11 §25.1/12:

In the description of the algorithms operators + and - are used for some of the iterator categories for which they do not have to be defined. In these cases the semantics of a+n is the same as that of

X tmp = a;
advance(tmp, n);
return tmp;

and that of b-a is the same as of return distance(a, b);


设计的通用性并没有内在的优势,它本身就是一个劣势,因为它更加冗长,并且对不正确的使用代码生成更难理解的诊断。它的优点包括上面列出的两个。显然,委员会认为这些优势,也许还有其他优势(?),超过了拥有 Size 的内在劣势。作为模板参数。

关于c++ - 为什么 std::copy_n 采用模板参数而不是 std::size_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522254/

相关文章:

c++ - 使用模式初始化 `constexpr` 数组

c++ - Raspberry 上的 Libtorch 无法加载 pt 文件但在 ubuntu 上工作

c++ - 为什么通用引用不适用于数组?

c++ - 结构定义导致我收到多重定义符号错误

c++ - E_INVALIDARG CreatePixelShader() 错误

c++ - std::unordered_map::emplace 问题与私有(private)/删除的复制构造函数

c++ - 常量成员初始化

c++ - 在 c++11 模式下使用 QtConcurrent::run with move only 参数

c++ - Windows 上带通配符的目录中的文件

c++ - malloc 有大小限制吗?