名稱空間
變體
操作

std::ranges::elements_of

來自 cppreference.com
< cpp‎ | ranges
 
 
範圍庫 (Ranges library)
範圍介面卡 (Range adaptors)
 
定義於標頭檔案 <ranges>
template< ranges::range R, class Allocator = std::allocator<std::byte> >
struct elements_of;
(C++23 起)

封裝一個 rangeelements_of 的特化在過載集中充當標籤,用於在範圍應被視為序列而非單個值時消除歧義。

目錄

[編輯] 模板引數

R - 滿足 range 的型別
Allocator - 滿足 Allocator 要求的分配器型別

[編輯] 資料成員

成員名稱 (Member name) 定義
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]