std::span<T,Extent>::first
From cppreference.com
 
 
 
 
 
 C++ 
 Feature test macros (C++20)
 Concepts library (C++20)
 Metaprogramming library (C++11)
 Ranges library (C++20)
 Filesystem library (C++17)
 Concurrency support library (C++11)
 Execution control library (C++26)
Containers library 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
(C++17)
(C++11)
(C++26)
(C++26)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++23)
(C++23)
(C++23)
(C++23)
(C++20)
(C++23)
 Tables
std::span 
 
 
 
 
 
 
(C++26)
(C++23)
(C++23)
(C++23)
(C++23)
span::first
template< std::size_t Count >
constexpr std::span <element_type, Count> first() const;
 (1) 
 (since C++20) 
constexpr std::span <element_type, Count> first() const;
constexpr std::span <element_type, std::dynamic_extent >
first( size_type count ) const;
 (2) 
 (since C++20) 
first( size_type count ) const;
Obtains a subview over the first Count or count elements of this span.
1) The element count is provided as a template argument, and the subview has a static extent.
 If Count > Extent is true, the program is ill-formed.
2) The element count is provided as a function argument, and the subview has a dynamic extent.
If Count > size() or count > size() is true, the behavior is undefined.
(until C++26)If Count > size() or count > size() is true:
- If the implementation is hardened, a contract violation occurs. Moreover, if the contract-violation handler returns under "observe" evaluation semantic, the behavior is undefined.
- If the implementation is not hardened, the behavior is undefined.
Contents
[edit] Parameters
 count
 -
 the number of the elements of the subview
[edit] Return value
1) std::span <element_type, Count>{data(), Count}
2) std::span <element_type, std::dynamic_extent >{data(), count}
[edit] Example
Run this code
#include <iostream> #include <ranges> #include <span> #include <string_view> void print(const std::string_view title, const std::ranges::forward_range auto& container) { auto size{std::size (container)}; std::cout << title << '[' << size << "]{"; for (const auto& elem : container) std::cout << elem << (--size ? ", " : ""); std::cout << "};\n"; } void run_game(std::span <const int> span) { print("span: ", span); std::span <const int, 5> span_first = span.first<5>(); print("span.first<5>(): ", span_first); std::span <const int, std::dynamic_extent > span_first_dynamic = span.first(4); print("span.first(4): ", span_first_dynamic); } int main() { int a[8]{1, 2, 3, 4, 5, 6, 7, 8}; print("int a", a); run_game(a); }
Output:
int a[8]{1, 2, 3, 4, 5, 6, 7, 8};
span: [8]{1, 2, 3, 4, 5, 6, 7, 8};
span.first<5>(): [5]{1, 2, 3, 4, 5};
span.first(4): [4]{1, 2, 3, 4};