Your team builds one C++20 codebase with GCC, Clang and MSVC; how do you decide how far to adopt std::ranges and views?
answer
- algorithms versus views
- the oldest standard library
- debug builds and compile times
- lifetime rules in review
- feature-test, then helper
basics
~20 sAdopt in tiers: ranges algorithms with projections broadly, as they stay eager; views for local one-pass pipelines under lifetime rules; C++23 pieces like ranges::to behind feature tests. The oldest shipped standard library and measured build and debug costs gate each tier.
solid answer
~50 sThere is no single answer, so separate the parts by risk. **Ranges algorithms** (`std::ranges::sort`, `find`, projections) are eager drop-in replacements with better diagnostics and dangling protection; they are easy to standardise once every supported standard library ships complete C++20 ranges, which you verify from each vendor's status page and `__cpp_lib_ranges`. **Views** change how code reads and carry new hazards - lazy side effects, views outliving their source, non-const filter views, duplicated transforms - so allow them where a one-pass local pipeline is clearer and ban storing or returning views over locals. **C++23** pieces such as `std::ranges::to` arrived later (libstdc++ 14.1, libc++ 17), so wrap them in a helper keyed on `__cpp_lib_ranges_to_container`. Measure compile time and unoptimised-build performance on representative code before mandating views in hot or engine code, write the rules into the style guide, and back them with review checklists and sanitizer-enabled tests.
code
cpp · 13 lines#include <cstdio>
#include <version>
int main() {
#if defined(__cpp_lib_ranges)
std::printf("__cpp_lib_ranges %ld\n", __cpp_lib_ranges);
#endif
#if defined(__cpp_lib_ranges_to_container)
std::printf("ranges::to available (%ld)\n", __cpp_lib_ranges_to_container);
#else
std::printf("no ranges::to: fall back to a loop or the vector(begin, end) constructor\n");
#endif
}go deeper
Know that ranges algorithms and views are different things, and that a team may allow one more freely than the other.
Explain why support depends on the standard library version and how feature-test macros like __cpp_lib_ranges report it.
Bring measured compile-time and debug-build numbers, and list the concrete lifetime and purity rules views need in review.
Own the tiered policy: what is allowed where, which toolchain floor gates each tier, how it is enforced, and when it is revisited.
## The decision is really three decisions "Adopt ranges" bundles features with very different risk profiles: | Tier | Examples | Behaviour change | Main risk | |---|---|---|---| | Ranges algorithms | `std::ranges::sort`, `find`, `max`, projections | none: still eager | standard library support | | Views and pipelines | `views::filter`, `transform`, `take`, `split` | lazy, reference semantics | lifetime bugs, surprising cost | | C++23 additions | `std::ranges::to`, `views::zip`, `views::enumerate`, `fold_left` | new APIs | uneven availability | Treating them separately lets a team take the cheap wins early without signing up for the hazards everywhere. ## Inputs to gather first 1. **The oldest toolchain you must build with.** Ranges arrived in libstdc++ 10.1 and were completed in libc++ 15 according to each project's own status pages; `std::ranges::to` came in libstdc++ 14.1 and libc++ 17. Read the MSVC STL's status the same way. The oldest compiler in your matrix - often a console SDK or a long-term-support Linux distribution - sets the floor, not the newest. 2. **Feature-test macros.** `__cpp_lib_ranges` and `__cpp_lib_ranges_to_container` (in `<version>`) say what the library provides in the current mode; a CI job per toolchain that prints them removes guesswork. 3. **Build cost.** Views are deeply nested templates. Measure compile time and object size on a few representative translation units before and after, rather than trusting anecdotes in either direction. 4. **Unoptimised performance.** Game, simulation and trading teams often run debug builds interactively. Nested view iterators depend on inlining; benchmark a hot pipeline at your debug optimisation level, not only at `-O2`. 5. **Diagnostics.** Concept errors from ranges algorithms are usually clearer than classic template errors, but a mistake deep in a long pipeline can still produce a wall of text. Try your team's typical mistakes on each compiler. ## A policy that tends to work - **Tier 1, broadly:** prefer `std::ranges` algorithms and projections in new code once every target library supports them. They remove comparator lambdas, catch misuse at the call, and return `std::ranges::dangling` for temporaries. - **Tier 2, locally:** allow views for one-pass pipelines consumed in the same scope. Forbid storing views in members or returning them when they refer to locals; require callables in views to be pure; pass views by value or forwarding reference, never `const&`. - **Tier 3, behind a helper:** expose `to_vector(r)` or similar that uses `std::ranges::to` when `__cpp_lib_ranges_to_container` is defined and a `std::ranges::copy` into a `back_inserter` otherwise, so call sites do not fork on the standard version. - **Hot paths:** allow views in performance-critical code only with a benchmark in the review, at both release and debug settings. ## Making the policy stick - Put the tiers in the style guide with one example each. - Add review checklist items: "does this view outlive its source?", "does a transform have side effects?", "is a filter view passed as `const&`?". - Run tests under AddressSanitizer, which catches many views-outliving-source bugs as use-after-free at run time. - Revisit when the oldest toolchain moves: raising the floor to C++23 removes the helper and unlocks `zip`, `enumerate` and `fold_left`. ## Rolling it out A staged rollout keeps the change reviewable: 1. **Pilot one module** that sorts, searches and filters a lot - the telemetry ingest, say - and convert it to ranges algorithms and a few local pipelines. 2. **Record the numbers**: compile time of the touched files, binary size, a release benchmark and a debug-build benchmark of the hot loop. 3. **Collect the review findings** from the pilot: which mistakes reviewers caught, which compiler errors confused people. 4. **Write the tiers and rules** from that evidence rather than from first principles, and publish them with the pilot as the worked example. 5. **Convert opportunistically** afterwards: new code follows the rules, old code changes only when it is touched for another reason, which avoids a churn-only mass rewrite. ## Arguments you will hear - *"Views are always zero-cost."* In optimised builds they often compile to the equivalent loop; in unoptimised builds and with expensive transforms below filters they may not. Measure. - *"Loops are clearer."* Sometimes. A three-stage pipeline usually reads better than a loop with three nested conditions; a pipeline with stateful lambdas usually reads worse. - *"Wait for C++23 everywhere."* Tier 1 needs only C++20 and pays off immediately; waiting forfeits it. The deliverable is not "yes" or "no" but a written, versioned rule set the team can apply without re-arguing it in every review.
- How would you keep call sites identical across C++20 and C++23 toolchains when materialising views?Provide one helper, for example `to_vector(r)`, that uses `std::ranges::to<std::vector>()` when `__cpp_lib_ranges_to_container` is defined and otherwise copies with `std::ranges::copy(r, std::back_inserter(out))`. Call sites use the helper only; when the oldest toolchain reaches C++23, the fallback branch is deleted and the helper can be inlined away.
- Which view rules would you enforce in code review from day one?No view stored in a member or returned from a function when it refers to a local or a parameter; callables inside views must be pure; views are passed by value or forwarding reference, never by `const&`; no writes through a filter view that change whether an element matches; and any view in a hot path ships with a benchmark at release and debug settings.
- Treating ranges adoption as one all-or-nothing switch
- Basing the decision on the newest compiler in the build matrix
- Claiming views are zero-cost without measuring debug builds
- Allowing views as class members over borrowed data
- Waiting for C++23 everywhere before using any ranges algorithm
Assumes C++23; ranges algorithms and views are C++20, std::ranges::to, zip, enumerate and fold_left are C++23.