|
BDE 4.39.x Production Release
|
Provide a (mostly) standard-compliant span class template.
Provide a (mostly) standard-compliant span class template.
std::span.bsl_span.h
This component provides the C+20 standard view type span, that is a view over a contiguous sequence of objects. Note that if compiler supports the C++20 standard, then the std implementation of span is used.
There are two implementations of span; one for statically sized (i. e., size fixed at compile time) spans, and dynamically sized (size can be altered at run-time).
bsl::span differs from std::span in the following ways:
constexpr inline symbol std::dynamic_extent has been replaced by an enumeration for C++03 compatibility.bsl::span can be implicitly constructed from a bsl::array.data() and size() is enabled only for C++11 and later.This section illustrates intended usage of this component.
Suppose we already have an array of values of type TYPE, and we want to pass a subset of the array to a function, which is expecting some kind of a container. We can create a span from the array, and then pass that. Since the span is a view into the array, i.e, the span owns no storage, the elements in the span are the same as the ones in the array.
First, we create a template function that takes a generic container. This function inspects each of the (numeric) values in the container, and if the low bit is set, flips it. This has the effect of turning odd values into even values.
We then create a span, and verify that it contains the values that we expect, and pass it to MakeEven to modify it. Afterwards, we check that none of the elements in the array that were not included in the span are unchanged, and the ones in the span were.
Suppose we already have a vector of values of type TYPE, and we want to return a (contiguous) subset of the vector from a function, which can then be processed processed using a range-based for loop. To achieve that, we can use span as the return type. The calling code can then interate over the span as if it was a container. Note that since the span doesn't own the elements of the vector, the span might become invalid when the vector is changed (or resized, or destroyed).
First, we create the vector and define our function that returns a slice as a span.
We can now iterate over the elements in the slice using the span:
Note that we can use the return value directly and avoid declaring the variable sp:
| #define BSLSTL_SPAN_IS_ALIASED |