std::ranges::elements_of
来自 cppreference.cn
定义于头文件 <ranges> |
||
template< ranges::range R, class Allocator = std::allocator<std::byte> > struct elements_of; |
(自 C++23 起) | |
封装一个 range
。elements_of
的特化在重载集中充当标签,以消除歧义,确定何时应将范围视为序列而不是单个值。
内容 |
[编辑] 模板参数
R | - | 满足 range 的类型 |
Allocator | - | 满足 Allocator 要求的分配器类型 |
[编辑] 数据成员
成员名称 | 定义 |
range |
类型为 R 的范围(公共成员对象) |
allocator |
类型为 Allocator 的分配器。它具有默认成员初始化器,对其自身进行值初始化(公共成员对象) |
所有这些成员都使用 [[no_unique_address]]
属性声明。
[编辑] 推导指引
template< class R, class Allocator = std::allocator<std::byte> > elements_of( R&&, Allocator = Allocator() ) -> elements_of<R&&, Allocator>; |
(自 C++23 起) | |
[编辑] 示例
运行此代码
#include <any> #include <generator> #include <iostream> #include <ranges> #include <string_view> template<bool Elementwise> std::generator<std::any> gen(std::ranges::input_range auto&& r) { if constexpr (Elementwise) co_yield std::ranges::elements_of(r); // yield each element of r else co_yield r; // yield r as a single value } int main() { auto test = std::string_view{"test"}; for (std::any a : gen<true>(test)) std::cout << '[' << std::any_cast<char>(a) << "] "; std::cout << '\n'; for (std::any a : gen<false>(test)) std::cout << '[' << std::any_cast<std::string_view>(a) << "] "; std::cout << '\n'; }
输出
[t] [e] [s] [t] [test]
[编辑] 参考
- C++23 标准 (ISO/IEC 14882:2024)
- 26.5.6 类模板 elements_of [range.elementsof]