Difference between revisions of "cpp/ranges/range adaptor closure"
From cppreference.com
D41D8CD98F (Talk | contribs) m |
m (langlink:zh) |
||
Line 53: | Line 53: | ||
345 | 345 | ||
}} | }} | ||
+ | |||
+ | {{langlinks|de|zh|es|ja|ru}} |
Revision as of 18:35, 26 September 2023
Defined in header <ranges>
|
||
template< class D > requires std::is_object_v<D> && std::same_as<D, std::remove_cv_t<D>> |
(since C++23) | |
std::ranges::range_adaptor_closure
is a helper class template for defining a RangeAdaptorClosureObject.
Let t
be the object of type T
, the implementation ensures that t
is a range adaptor closure object if all the requirements are met:
-
t
is a unary function object that takes onerange
argument. -
T
has exactly one public base class ranges::range_adaptor_closure<T>, and T has no base classes of type ranges::range_adaptor_closure<U> for any other type U. -
T
does not satisfyrange
.
Example
Run this code
#include <iostream> #include <ranges> #include <string> #include <string_view> // define Slice as a range adaptor closure struct Slice : std::ranges::range_adaptor_closure<Slice> { std::size_t start = 0; std::size_t end = std::string_view::npos; std::string_view operator()(std::string_view sv) const { return sv.substr(start, end - start); } }; int main() { std::string str = "01234567"; Slice slicer{.start = 1, .end = 6}; auto sv1 = slicer(str); // use slicer as a normal function object auto sv2 = str | slicer; // use slicer as a range adaptor closure object std::cout << sv1 << '\n'; std::cout << sv2 << '\n'; // range adaptor closures can be composed auto slice_and_drop = slicer | std::views::drop_while([](auto ch) { return ch != '3'; }); std::cout << std::string_view(str | slice_and_drop) << '\n'; }
Output:
12345 12345 345