std::span
and
std::string_view
interfacesstd::span
and
std::string_view
interfaces| Document #: | P3837R0 Latest Status |
| Date: | 2026-11-25 |
| Project: | Programming Language C++ |
| Audience: |
Library Evolution Working Group Library Working Group |
| Reply-to: |
Mateusz Pusz <mateusz.pusz@gmail.com> |
This paper proposes to unify the interfaces of
std::span
and
std::string_view
by adding missing member functions to both types. The proposed
changes:
first and
last member functions to
std::string_viewremove_prefix and
remove_suffix member functions to
dynamic-sized
std::spanstd::span
and
std::string_view
are both lightweight, non-owning views over contiguous sequences in the
C++ Standard Library. They serve similar purposes but have inconsistent
interfaces that complicate generic programming and increase cognitive
load.
Consider the following operations:
std::string_view sv = "Hello, World!";
std::span sp{sv.data(), sv.size()}; // dynamic-sized span
// Getting first N elements
auto first5_sv = sv.substr(0, 5); // "Hello"
auto first5_sp = sp.first(5); // equivalent span
// Getting last N elements
auto last6_sv = sv.substr(sv.size() - 6); // "World!"
auto last6_sp = sp.last(6); // equivalent span
// Removing prefix
sv.remove_prefix(7); // "World!"
// sp.remove_prefix(7); // ERROR: no such member function
// Removing suffix
sv.remove_suffix(1); // "World"
// sp.remove_suffix(1); // ERROR: no such member functionThis inconsistency forces developers to:
Here’s an example of generic code that currently requires specialization:
template<typename View>
void process_middle_part(View& view) {
if constexpr (std::is_same_v<View, std::string_view>) {
view.remove_prefix(1);
view.remove_suffix(1);
} else if constexpr (requires { view.first(1); }) {
// For span, we need to reassign since remove_* don't exist
auto size = view.size();
view = view.subspan(1, size - 2);
}
}With unified interfaces, this becomes simply:
template<typename View>
void process_middle_part(View& view) {
view.remove_prefix(1);
view.remove_suffix(1);
}Note: The above simplified example assumes the view is
dynamically-sized
(std::string_view
or
std::span<T, std::dynamic_extent>).
For fixed-size spans, remove_prefix
and remove_suffix
are not available, requiring conditional compilation or concepts to
handle both cases.
The current state of
std::span
and
std::string_view
interfaces creates several issues:
Operation
|
std::string_view
|
std::span
|
Generic Code Impact
|
|---|---|---|---|
| Get first N elements | substr(0, n) |
first(n) |
Requires different APIs |
| Get last N elements | substr(size()-n) |
last(n) |
Requires different APIs |
| Remove prefix | remove_prefix(n) |
❌ Missing | Forces workarounds |
| Remove suffix | remove_suffix(n) |
❌ Missing | Forces workarounds |
Writing generic algorithms that work with both types requires template specialization or SFINAE techniques, increasing complexity and reducing maintainability.
New C++ developers must learn different interfaces for conceptually similar operations, violating the principle of least surprise.
We propose to add the missing member functions to both types, making their interfaces consistent and complete.
std::string_viewconstexpr string_view first(size_type n) constconstexpr string_view last(size_type n) conststd::spanconstexpr void remove_prefix(size_type n)
(dynamic extent only)constexpr void remove_suffix(size_type n)
(dynamic extent only)Note: The remove_prefix
and remove_suffix functions are only
added to
span<T, dynamic_extent>
because fixed-size spans cannot change their extent. This preserves
semantic consistency with
string_view behavior (in-place
modification) while avoiding the confusion that would arise from having
the same function names perform different operations (modification
vs. returning new views).
The proposed solution is fully backward compatible:
Example of enhanced generic code:
// Before: Complex, type-specific code
template<typename View>
auto get_middle(const View& view) {
if constexpr (std::is_same_v<View, std::string_view>) {
return view.substr(1, view.size() - 2);
} else {
return view.subspan(1, view.size() - 2);
}
}
// After: Simple, unified interface for dynamic spans and string_view
template<typename View>
void trim_ends(View& view) {
if constexpr (requires { view.remove_prefix(1); }) {
// Works for string_view and dynamic span
view.remove_prefix(1);
view.remove_suffix(1);
} else {
// Fallback for fixed span
view = view.subspan(1, view.size() - 2);
}
}
// For cases where you know you have a dynamic span or string_view:
template<typename DynamicView>
requires requires(DynamicView& v) { v.remove_prefix(1); v.remove_suffix(1); }
void trim_ends_simple(DynamicView& view) {
view.remove_prefix(1); // Works for both!
view.remove_suffix(1); // Works for both!
}The most critical design decision in this proposal is how to handle
remove_prefix and
remove_suffix for fixed-size spans
(span<T, N>
where
N != dynamic_extent).
Since fixed-size spans cannot change their extent, these functions
cannot perform in-place modification as they do for
string_view.
We thoroughly analyzed three potential approaches:
first/last)// Hypothetical approach - NOT proposed
template<size_t Extent>
constexpr auto remove_prefix(size_type n) const -> span<element_type, Extent == dynamic_extent ? dynamic_extent : (Extent - n)>;
template<size_t Extent>
constexpr auto remove_suffix(size_type n) const -> span<element_type, Extent == dynamic_extent ? dynamic_extent : (Extent - n)>;remove_prefix/remove_suffix)
would have fundamentally different behaviors:
string_view::remove_prefix(n)
- modifies the view in-place, returns
voidspan::remove_prefix(n)
- returns a new view, original unchangedstring_view could behave
unexpectedly with spanspan would be the only standard
library type where these function names don’t modify in-placetemplate<typename View>
void process_data(View& view) {
auto original_size = view.size();
view.remove_prefix(10); // What does this do?
// For string_view: view is modified, size() != original_size
// For span: view unchanged, size() == original_size
// This semantic difference could cause silent bugs
}// For dynamic spans only
constexpr void remove_prefix(size_type n); // In-place modification
constexpr void remove_suffix(size_type n); // In-place modification
// For all spans
constexpr auto trim_prefix(size_type n) const; // Returns new view
constexpr auto trim_suffix(size_type n) const; // Returns new viewtemplate<typename View>
void trim_edges(View& view) {
if constexpr (requires { view.remove_prefix(1); }) {
view.remove_prefix(1); // Modify in-place
view.remove_suffix(1);
} else {
view = view.trim_prefix(1); // Different function name!
view = view.trim_suffix(1);
}
}// Add to std::string_view
constexpr string_view trim_prefix(size_type n) const; // Returns new view
constexpr string_view trim_suffix(size_type n) const; // Returns new view
// For all spans (existing functionality)
constexpr auto trim_prefix(size_type n) const; // Returns new view
constexpr auto trim_suffix(size_type n) const; // Returns new viewThis would maintain complete interface consistency by providing
view-returning functions
across both types while keeping the in-place modification
functions
(remove_prefix/remove_suffix)
available where semantically appropriate.
trim_*
returns new views,
remove_*
modifies in-placetrim_*
functionsstring_viewsv.trim_prefix(n)
vssv.substr(n))string_view
currently usessubstr for view creationtrim_prefix(n)
is essentially equivalent to
substr(n)trim_suffix(n)
to
substr(0, size() - n)template<typename View>
auto get_middle_part(const View& view) {
// Works universally - always returns a new view
return view.trim_prefix(1).trim_suffix(1);
}Note: While this alternative would provide complete
interface symmetry, the
trim_*
functions
can always be added in a future proposal if deemed valuable after
gaining experience with the
core unified interface.
// Only available for span<T, dynamic_extent>
constexpr void remove_prefix(size_type n); // Modifies in-place
constexpr void remove_suffix(size_type n); // Modifies in-placeremove_prefix/remove_suffix
always mean “modify in-place” across all typesvector::push_back
not available for arrays)requires
expressions or SFINAE for fallbackstemplate<typename View>
void trim_edges(View& view) {
if constexpr (requires { view.remove_prefix(1); }) {
// Works for string_view and dynamic span
view.remove_prefix(1);
view.remove_suffix(1);
} else {
// Clear fallback for fixed span
view = view.subspan(1, view.size() - 2);
}
}We chose Alternative 3 (only dynamic spans) for the following reasons:
The most important principle is that identical function names should
have identical semantics across the standard library. Having
remove_prefix mean “modify in-place”
for string_view but “return new
view” for span would violate this
fundamental design principle.
It’s better to get a clear compilation error when trying to use
remove_prefix on a fixed span than
to have the same code work but behave differently for different
types.
The standard library already has extent-specific operations for the same class template:
std::span<T, N>::subspan<Count, Offset>()
- compile-time version only available forstd::array<T, N>::fill()
- available for
std::array
but not for generic containersstd::vector<bool>
vs
std::vector<T>)This follows the principle that member function availability should
match the type’s semantic
capabilities.
Modern C++ provides excellent tools
(requires
expressions, concepts) for handling type-specific capabilities in
generic code, making this a manageable constraint.
Avoiding function name proliferation keeps the interface clean and teachable.
We also considered adding non-type template parameter (NTTP)
overloads to
std::string_view:
template<size_t N> constexpr string_view first() consttemplate<size_t N> constexpr string_view last() consttemplate<size_t N> constexpr string_view substr() constHowever, we decided against including these for several reasons:
string_view: Unlike
span<T, N>,
string_view isThe chosen approach enables clean generic programming patterns:
template<typename View>
void trim_prefix(View& view, size_t n) {
if constexpr (requires { view.remove_prefix(n); }) {
// Works for string_view and dynamic span
view.remove_prefix(n);
} else {
// Fallback for fixed span - reassignment
view = view.subspan(n);
}
}
// For cases where you know the view supports modification:
template<typename ModifiableView>
requires requires(ModifiableView& v) { v.remove_prefix(1); }
void trim_prefix_simple(ModifiableView& view) {
view.remove_prefix(1); // Always modifies in-place
}This approach provides:
requires
expressions enable appropriate fallbacksThe new functions follow the same semantics and exception guarantees as their existing counterparts:
string_view::first/last:
Same behavior as
span::first/lastspan::remove_prefix/remove_suffix:
Same behavior as
string_view::remove_prefix/remove_suffixn <= size()
for all functionsnoexcept
specification matches existing patternsWe maintain existing naming conventions:
first/last
return new views (following span
convention)remove_prefix/remove_suffix
modify the current view (following
string_view convention)The new functions are implemented as simple forwarding operations with no performance overhead:
// string_view::first implementation
constexpr string_view first(size_type n) const {
return substr(0, n);
}
// span::remove_prefix implementation
constexpr void remove_prefix(size_type n) {
*this = subspan(n);
}Several implementations have been prototyped, confirming:
The proposed changes are relative to [@!N5008].
namespace std {
template<class charT, class traits = char_traits<charT>>
class basic_string_view {
// ...
constexpr basic_string_view substr(size_type pos = 0, size_type n = npos) const;
+ constexpr basic_string_view first(size_type n) const;
+ constexpr basic_string_view last(size_type n) const;
constexpr void remove_prefix(size_type n);
constexpr void remove_suffix(size_type n);
// ...
};
}namespace std {
template<class ElementType, size_t Extent = dynamic_extent>
class span {
// ...
template<size_t Count> constexpr span<element_type, Count> first() const;
constexpr span<element_type, dynamic_extent> first(size_type count) const;
template<size_t Count> constexpr span<element_type, Count> last() const;
constexpr span<element_type, dynamic_extent> last(size_type count) const;
// ...
};
+ // Additional members for dynamic extent spans only
+ template<class ElementType>
+ class span<ElementType, dynamic_extent> {
+ // ... (all existing members)
+ constexpr void remove_prefix(size_type n);
+ constexpr void remove_suffix(size_type n);
+ };
}+constexpr basic_string_view first(size_type n) const;Preconditions:
n <= size().
Returns:
substr(0, n).
+constexpr basic_string_view last(size_type n) const;Preconditions:
n <= size().
Returns:
substr(size() - n, n).
Note: The following member functions are only available for
span<ElementType, dynamic_extent>.
+constexpr void remove_prefix(size_type n);Preconditions:
n <= size().
Effects: Equivalent to:
*this = subspan(n);.
+constexpr void remove_suffix(size_type n);Preconditions:
n <= size().
Effects: Equivalent to:
*this = subspan(0, size() - n);.
Add the following feature test macro to [version.syn]:
+#define __cpp_lib_unified_span_string_view 202509L // also in <span> and <string_view>This proposal lays the groundwork for:
The unified interface also enables future proposals for:
Special thanks and recognition goes to The C++ Alliance for supporting Mateusz’s membership in the ISO C++ Committee and the production of this proposal.
Additional thanks to the C++ community for feedback on interface consistency issues and generic programming challenges with the current standard library.