Namespaces
Variants

std::ranges:: elements_of

From cppreference.net
Ranges library
Range adaptors
定义于头文件 <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); // 逐个生成 r 的元素
    else
        co_yield r;                           // 将 r 作为单个值生成
}
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]