Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Range adaptor pipe operator `|`

Use `|` to apply an adaptor closure to a range or compose two closures into a reusable pipeline. This overload is distinct from built-in bitwise OR.

Version: ISO C++23; implementation support may vary

Syntax

r | c
c | d
r | c | d
r | (c | d)
r | std::views::filter(pred) | std::views::transform(fn)

The range adaptor pipe (|) is an overload of operator| provided by <ranges>. When c is a range adaptor closure that accepts r, r | c is equivalent to c(r). Calling std::views::filter(pred) binds the predicate without supplying the range yet. std::views is an alias for std::ranges::views.

c | d builds a closure that stores both stages without taking a range yet. r | c | d groups as (r | c) | d, while r | (c | d) composes the stages first. When both forms are well-formed, they apply c and then d, as in d(c(r)). Composition, however, must initialize its stored closures from the operands. For example, a move-only closure may be callable directly as an lvalue, but composing it from that lvalue would require a copy. By contrast, 1 | 2 uses built-in bitwise OR and produces 3. An ordinary lambda is not enough on the right: r | pred is ill-formed without a matching overload.

filter exposes only matching elements, and transform computes a result when an element is read. The pipeline produces a view, not a new container of results. In the example, the view refers to values; the array must stay alive while the view is used. The same lifetime rule applies to objects captured by reference and used by the stages.

The standard filter and transform adaptors support pipes from C++20. C++23 adds std::ranges::range_adaptor_closure for defining your own pipeable closures. Support depends on the standard library and the selected compilation mode.

Examples

#include <array>
#include <iostream>
#include <ranges>

int main() {
    const std::array values{1, 2, 3, 4, 5};
    auto pipeline = std::views::filter([](int n) { return n % 2 == 0; })
                  | std::views::transform([](int n) { return n * 10; });

    auto result = values | pipeline;
    for (int n : result) {
        std::cout << n << '\n';
    }
}

Result

20
40

The program composes the two stages first, then applies them to `values`. It prints `20` and `40` on separate lines.

Related lessons

  • C++ · Lesson 26 · Advanced · Version: 3
  • C++ · Lesson 29 · Advanced · Version: 3

Sources