span<T>
or a span_p<T>
to designate a half-open sequenceF.24:使用span<T>或者span_p<T>表示半开序列
译者注
译者注:半开是数学概念,指的是C++中的数组用[p:p+n)表示时,p指向第一个元素,而p+n则处于数组之外。
Informal/non-explicit ranges are a source of errors.
非正式的,不清楚的范围是错误之源。
X* find(span<X> r, const X& v); // find v in r
vector<X> vec;
// ...
auto p = find({vec.begin(), vec.end()}, X{}); // find X{} in vec
Ranges are extremely common in C++ code. Typically, they are implicit and their correct use is very hard to ensure. In particular, given a pair of arguments (p, n)
designating an array [p:p+n)
, it is in general impossible to know if there really are n
elements to access following *p
.span<T>
and span_p<T>
are simple helper classes designating a [p:q)
range and a range starting with p
and ending with the first element for which a predicate is true, respectively.
在C++代码中,范围的概念特别常见。典型情况下,范围不会被明示而且很难确认是否被正常使用。尤其,给定一对表示参数(p, n)以表示数组[n:p+n),通常不可能知道p的后面是否真有n个元素可用。作为简单的辅助类,span<T>用于表明范围[p:q),而span_p<T>用于表示的范围开始于p,终止于第一个谓词为true的元素。
译者注:很遗憾没有找到span_p<T>的用法示例。
A span
represents a range of elements, but how do we manipulate elements of that range?
span表示元素的范围,但是我们怎么操作范围中的元素呢?
void f(span<int> s)
{
// range traversal (guaranteed correct)
for (int x : s) cout << x << '\n';
// C-style traversal (potentially checked)
for (gsl::index i = 0; i < s.size(); ++i) cout << s[i] << '\n';
// random access (potentially checked)
s[7] = 9;
// extract pointers (potentially checked)
std::sort(&s[0], &s[s.size() / 2]);
}
A span<T>
object does not own its elements and is so small that it can be passed by value.
span<T>对象不会真正用于它的元素,小到可以直接传递对象。
Passing a span
object as an argument is exactly as efficient as passing a pair of pointer arguments or passing a pointer and an integer count.
传递span对象作为参数和传递一对指针参数或者一个指针一个整数在高效性方面完全相同。
See also: Support library
参见:支持库。https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-gsl
(Complex) Warn where accesses to pointer parameters are bounded by other parameters that are integral types and suggest they could use span
instead.
(复杂)当代码访问以整形值确定边界的指针类型参数时,报警并建议使用span代替。