Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Type design: unions, newtypes & generics

Using the type system to rule out bugs: models in which invalid states cannot be built, newtypes for IDs and units, checks that every case is handled, states encoded as types, constrained generics, variance and higher-kinded types. It goes deeper than the Types & syntax entries, which show how to read generics and tagged variants, and the Paradigms entries, which introduce algebraic data types.

Make illegal states unrepresentable: unions over flags, parse don't validate, smart constructors

C++

Name alternatives and tagged variants (Types & syntax) shows how to write a union; this entry uses unions and validated constructors to design a model in which nonsense combinations cannot be built. A class with a private constructor and a static parse returning std::expected<Email, std::string> (C++23) guarantees that every Email has been validated. std::variant replaces groups of optional fields and flags: Reach is one of ByEmail, ByPhone or ByBoth, so a contact with no way to reach it cannot exist. parse_contact runs once at the boundary and returns either a complete Contact or an error string, and std::visit makes each consumer handle every shape.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <expected>
#include <optional>
#include <print>
#include <string>
#include <string_view>
#include <utility>
#include <variant>

// Smart constructor: the constructor is private, so parse is the only way in.
class Email {
public:
    static std::expected<Email, std::string> parse(std::string_view raw) {
        auto at = raw.find('@');
        if (at == 0 || at == raw.npos || raw.find('.', at) == raw.npos)
            return std::unexpected("bad email: " + std::string(raw));
        return Email{std::string(raw)};
    }
    const std::string& str() const { return value_; }

private:
    explicit Email(std::string v) : value_(std::move(v)) {}
    std::string value_;
};

// Before: optional<string> email, phone, where both empty is invalid but representable.
// After: a variant whose alternatives are only the valid shapes.
struct ByEmail { Email email; };
struct ByPhone { std::string phone; };
struct ByBoth { Email email; std::string phone; };
using Reach = std::variant<ByEmail, ByPhone, ByBoth>;
struct Contact { std::string name; Reach reach; };

template <class... Fs>
struct overloaded : Fs... { using Fs::operator()...; };

// Parse once at the boundary.
std::expected<Contact, std::string> parse_contact(std::string name, std::optional<std::string_view> email,
                                                  std::optional<std::string> phone) {
    if (!email && !phone) return std::unexpected("need an email or a phone");
    if (!email) return Contact{std::move(name), ByPhone{std::move(*phone)}};
    auto e = Email::parse(*email);
    if (!e) return std::unexpected(e.error());
    if (!phone) return Contact{std::move(name), ByEmail{std::move(*e)}};
    return Contact{std::move(name), ByBoth{std::move(*e), std::move(*phone)}};
}

std::string send_to(const Contact& c) {
    return std::visit(overloaded{
        [](const ByEmail& r) { return "mail " + r.email.str(); },
        [](const ByBoth& r) { return "mail " + r.email.str(); },
        [](const ByPhone& r) { return "text " + r.phone; },
    }, c.reach);
}

int main() {
    auto ana = parse_contact("Ana", "ana@example.com", std::nullopt);
    auto lee = parse_contact("Lee", std::nullopt, "+15550100");
    assert(ana && lee);
    // Email fake{"x"};
    //   error: calling a private constructor of class 'Email'
    assert(!parse_contact("Nobody", std::nullopt, std::nullopt));
    assert(!parse_contact("Bad", "nope", std::nullopt));
    std::println("{} | {}", send_to(*ana), send_to(*lee));
}

In practice: keep invariants in classes whose constructors cannot produce an invalid object (private constructor plus a factory, or a constructor that throws), and avoid std::optional fields whose presence depends on another field. Before C++23, return std::optional or throw from the factory instead of std::expected.

Copying and moving still work with a private constructor (the implicit copy and move constructors stay public), which is what lets Contact hold an Email by value.

A moved-from Email has an unspecified string; if that matters, delete the move operations or re-check in accessors.

Wrap a primitive in a distinct type: brands, defined types, tuple structs, strong typedefs

C++

Where Name alternatives and tagged variants (Types & syntax) names a set of values, a newtype gives one kind of value its own type, so two values with the same representation (two string IDs, meters and feet) cannot be swapped. typedef and using only create aliases, so `using UserId = std::string` protects nothing. A strong typedef is a small struct around the value with an explicit constructor: the compiler no longer converts in or out, and only the operations you declare exist (a defaulted operator<=> gives comparisons with the same type only). For integers, an enum class with a fixed underlying type and no enumerators does the same in one line; it can be built with Cents{250} and unwrapped with std::to_underlying (C++23). std::chrono::duration is the standard library's own strong type for time units.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <chrono>
#include <compare>
#include <cstdint>
#include <print>
#include <string>
#include <utility>

// A struct wrapper with an explicit constructor: no implicit conversion in or out.
struct UserId {
    explicit UserId(std::string v) : value(std::move(v)) {}
    std::string value;
    auto operator<=>(const UserId&) const = default;  // ==, <, ... only against UserId
};

struct OrderId {
    explicit OrderId(std::string v) : value(std::move(v)) {}
    std::string value;
    auto operator<=>(const OrderId&) const = default;
};

// For integers, an enum class with no enumerators is a cheap strong typedef:
// it has the size of its underlying type and never converts implicitly.
enum class Cents : std::int64_t {};

constexpr Cents operator+(Cents a, Cents b) {
    return Cents{std::to_underlying(a) + std::to_underlying(b)};  // C++23 to_underlying
}

std::string cancel_order(const UserId& user, const OrderId& order) {
    return user.value + " cancelled " + order.value;
}

int main() {
    UserId u{"u_42"};
    OrderId o{"o_9001"};
    std::println("{}", cancel_order(u, o));
    // cancel_order(o, u);
    //   error: no matching function for call to 'cancel_order'
    // cancel_order(std::string("u_42"), o);
    //   error: no matching function (an explicit constructor never converts implicitly)

    Cents price{250};  // direct-list-initialization from an integer is allowed (C++17)
    Cents total = price + Cents{199};
    // Cents bad = 250;   error: cannot initialize a variable of type 'Cents' with an rvalue of type 'int'
    // int raw = total;   error: cannot initialize a variable of type 'int' with an lvalue of type 'Cents'
    assert(std::to_underlying(total) == 449);
    std::println("total {}", std::to_underlying(total));

    // The standard library does this for time: seconds and milliseconds are distinct types,
    // and lossless conversions happen implicitly while lossy ones need duration_cast.
    std::chrono::milliseconds ms = std::chrono::seconds{3};
    auto whole = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::milliseconds{3500});
    std::println("{} {}", ms, whole);
}

In practice: wrap IDs and units in a struct with an explicit constructor, and add operators only where the arithmetic makes sense. Use the enum class trick for integer IDs and handles.

An enum class with no enumerators still allows static_cast from any integer, so it marks intent rather than validating.

Brace-initializing an enum class from an integer (Cents{250}) needs C++17; Cents c = 250 is still an error.

A struct wrapper is a zero-cost abstraction with optimization on; it is the same size as its field.

Make the compiler check every case: assertNever, exhaustive linters, match, std::visit

C++

Algebraic data types (in Paradigms) shows how to build a sum type with std::variant; this entry covers the compile-time checks that catch a missing case. std::visit with a set of lambdas (the overloaded helper) checks that every alternative has a matching call; a missing one fails to compile. A switch over an enum class has no such guarantee in the language, but Clang and GCC warn with -Wswitch (on under -Wall) when a switch without a default misses an enumerator. An enum class can still hold any value of its underlying type, so code after a full switch is reachable in principle.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <print>
#include <string>
#include <utility>
#include <variant>
#include <vector>

struct EmailNotice { std::string address; };
struct SmsNotice { std::string phone; };
struct PushNotice { std::string device_id; };
using Notice = std::variant<EmailNotice, SmsNotice, PushNotice>;

// The overloaded helper: one lambda per alternative.
template <class... Fs>
struct overloaded : Fs... { using Fs::operator()...; };

std::string target(const Notice& n) {
    // Leaving out the PushNotice lambda is a compile error; libc++ says:
    // static assertion failed: `std::visit` requires the visitor to be exhaustive.
    return std::visit(overloaded{
        [](const EmailNotice& e) { return e.address; },
        [](const SmsNotice& s) { return s.phone; },
        [](const PushNotice& p) { return p.device_id; },
    }, n);
}

enum class Delivery { Queued, Sent, Failed };

const char* name(Delivery d) {
    // No default: with -Wall (which enables -Wswitch), a missing enumerator warns:
    // warning: enumeration value 'Failed' not handled in switch [-Wswitch]
    // Add -Werror=switch to make it an error.
    switch (d) {
        case Delivery::Queued: return "queued";
        case Delivery::Sent: return "sent";
        case Delivery::Failed: return "failed";
    }
    // An enum class can still hold other values, e.g. static_cast<Delivery>(9).
    std::unreachable();  // C++23: undefined behavior if reached, so only after a full switch
}

int main() {
    const std::vector<Notice> notices{
        EmailNotice{"ana@example.com"}, SmsNotice{"+15550100"}, PushNotice{"dev-7"}};
    for (const Notice& n : notices) std::println("{}", target(n));
    assert(target(notices[2]) == "dev-7");
    std::println("{} {} {}", name(Delivery::Queued), name(Delivery::Sent), name(Delivery::Failed));
}

In practice: use std::variant plus std::visit for closed sets that carry data. For enum class, write switches with no default so -Wswitch can see a missing enumerator, build with -Werror=switch, and after the switch handle the out-of-range case explicitly (an error, or std::unreachable when the value is known valid).

A generic catch-all lambda, [](const auto&) { ... }, matches every alternative and silences the check, like _ in Rust.

Overload resolution picks the lambda, so implicit conversions can route an alternative to the wrong case (an int alternative to a lambda taking long). Use exact types.

Adding a default label to an enum switch turns -Wswitch off for it; -Wswitch-enum warns even then, but is noisy.

std::unreachable needs C++23 (<utility>); reaching it is undefined behavior.

Allow a call only in the right state (typestate): state types, consuming self, PhantomData, tag templates

C++

Name alternatives and tagged variants (Types & syntax) puts every state in one union; typestate gives each state its own type, so a call that is wrong for the current state does not compile. C++ can express typestate with distinct classes per state, private constructors and friend transition functions, so the only way to get a Published is publish(Draft&&). The template style uses empty tag types, Conn<Connected>, and a requires-clause on each member function (C++20) so send exists only when State is Connected; a call on Conn<Disconnected> fails with "constraints not satisfied". A && qualifier on a member function makes it callable only on an rvalue, which signals that the transition consumes the object.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <concepts>
#include <optional>
#include <print>
#include <string>
#include <utility>
#include <vector>

// Part 1: distinct types per state. Constructors are private; transitions are friends.
class Published;

class Draft {
public:
    explicit Draft(std::string title) : title_(std::move(title)) {}
    Draft edit(std::string body) && {  // &&: callable only on a temporary or std::move(d)
        body_ = std::move(body);
        return std::move(*this);
    }
    friend std::optional<Published> publish(Draft&& d);

private:
    std::string title_, body_;
};

class Published {
public:
    std::string url() const { return "/posts/" + title_; }

private:
    explicit Published(std::string title) : title_(std::move(title)) {}
    friend std::optional<Published> publish(Draft&& d);
    std::string title_;
};

std::optional<Published> publish(Draft&& d) {
    if (d.body_.empty()) return std::nullopt;
    return Published{std::move(d.title_)};
}

// Part 2: one template with tag types, and requires-clauses that gate members per state.
struct Disconnected {};
struct Connected {};

template <class State>
class Conn {
public:
    explicit Conn(std::string addr) requires std::same_as<State, Disconnected>
        : addr_(std::move(addr)) {}

    Conn<Connected> connect() && requires std::same_as<State, Disconnected> {
        return Conn<Connected>{std::move(addr_), std::move(sent_)};
    }
    void send(std::string msg) requires std::same_as<State, Connected> {
        sent_.push_back(std::move(msg));
    }
    const std::vector<std::string>& sent() const { return sent_; }

private:
    template <class> friend class Conn;
    Conn(std::string addr, std::vector<std::string> sent)
        : addr_(std::move(addr)), sent_(std::move(sent)) {}
    std::string addr_;
    std::vector<std::string> sent_;
};

int main() {
    auto post = publish(Draft{"type-state"}.edit("States as types."));
    assert(post.has_value());
    // Published direct{"x"};
    //   error: calling a private constructor of class 'Published'
    assert(!publish(Draft{"empty"}).has_value());

    Conn<Disconnected> conn{"db:5432"};
    // conn.send("ping");
    //   error: invalid reference to function 'send': constraints not satisfied
    auto live = std::move(conn).connect();
    live.send("ping");
    live.send("query");
    // Pitfall: C++ does not stop use after move. conn still exists in a valid but
    // unspecified state; clang-tidy's bugprone-use-after-move check flags reuse.
    std::println("{} sent {}", post->url(), live.sent());
}

In practice: use tag templates for builders and protocol objects, and requires-clauses rather than SFINAE. Mark transitions && and call them on std::move(x) or a temporary. C++ cannot stop use after move, so pair this with clang-tidy's bugprone-use-after-move check.

A moved-from object is valid but unspecified; the compiler accepts calls on it. The template style limits the damage because a moved-from Conn<Disconnected> still has no send.

Before C++20, the same gating needs std::enable_if or separate specializations.

Printing a std::vector with std::println needs range formatting: GCC 15+ (libstdc++) or libc++ 17+.

Constrain a generic type: extends + keyof, type sets, trait bounds, concepts

C++

Read a type parameter (Types & syntax) shows how to read template <typename T>; this entry covers writing the constraint that says what T must support. C++20 concepts are named compile-time predicates on types. A standard concept can replace typename (template <std::totally_ordered T>), a custom concept uses a requires-expression to list what must compile and what it must return ({ t.id() } -> std::convertible_to<std::string>), and a requires-clause combines them with && and ||. `std::integral auto n` is the abbreviated form. When two overloads both match, the more constrained one wins (signed_integral subsumes integral).

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <algorithm>
#include <cassert>
#include <concepts>
#include <print>
#include <string>
#include <vector>

// A standard concept as a constraint: T must support <, >, <=, >=, == and !=.
template <std::totally_ordered T>
T largest(const std::vector<T>& xs) {
    return *std::ranges::max_element(xs);
}

// A custom concept: a requires-expression lists what must compile, with result types.
template <class T>
concept HasId = requires(const T& t) {
    { t.id() } -> std::convertible_to<std::string>;
};

// A requires-clause after the template header can combine concepts.
template <class T>
    requires HasId<T> && std::copyable<T>
std::vector<std::string> ids(const std::vector<T>& items) {
    std::vector<std::string> out;
    for (const T& item : items) out.push_back(item.id());
    return out;
}

// Abbreviated syntax: a constrained auto parameter (C++20).
auto twice(std::integral auto n) { return n * 2; }

// Overloads ranked by concept: the more constrained one wins when both match.
template <std::integral T>
std::string kind(T) { return "integral"; }
template <std::signed_integral T>
std::string kind(T) { return "signed integral"; }  // signed_integral subsumes integral

struct User {
    std::string name;
    std::string id() const { return "u_" + name; }
};

int main() {
    assert(largest(std::vector{3, 9, 4}) == 9);
    std::println("{}", ids(std::vector<User>{{"ana"}, {"lee"}}));
    std::println("{} {} {}", twice(21), kind(5), kind(5u));
    // twice(1.5);
    //   error: no matching function for call to 'twice'
    //   note: because 'double' does not satisfy 'integral'
    // ids(std::vector<int>{1});
    //   note: because 'int' does not satisfy 'HasId'
}

In practice: constrain every template that has a public interface. Errors then name the unmet concept at the call ("'double' does not satisfy 'integral'") instead of failing deep inside the template body. Prefer the standard concepts in <concepts>, <iterator> and <ranges> before writing your own.

Subsumption works only between named concepts. Two requires-clauses that spell the same expression are not recognized as related, and the call becomes ambiguous.

A concept checks that expressions compile, not what they mean: a type with an id() returning a number convertible to string still satisfies HasId.

Printing a std::vector with std::println needs range formatting: GCC 15+ (libstdc++) or libc++ 17+.

Know when subtypes substitute (variance): covariant arrays, invariant slices, lifetime subtyping, covariant returns

C++

Read a type parameter (Types & syntax) treats each instantiation on its own; variance is the rule for when a container of Dog can be used where a container of Animal is expected. Each template instantiation is an unrelated type, so templates are invariant: std::vector<Dog*> does not convert to std::vector<Animal*>, even though Dog* converts to Animal*. Build a new vector with the iterator-range constructor, which converts element by element. The one place C++ has covariance is virtual functions: an override may return Dog* or Dog& where the base returns Animal* or Animal&. That does not extend to smart pointers, so a std::unique_ptr<Dog> clone() cannot override a std::unique_ptr<Animal> clone().

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <concepts>
#include <memory>
#include <print>
#include <ranges>
#include <string>
#include <vector>

struct Animal {
    virtual ~Animal() = default;
    virtual std::string name() const = 0;
    // Public, non-virtual and owning; the virtual part stays private.
    std::unique_ptr<Animal> clone() const { return std::unique_ptr<Animal>(do_clone()); }

private:
    virtual Animal* do_clone() const = 0;
};

struct Dog : Animal {
    std::string name() const override { return "Rex"; }
    std::string bark() const { return "woof"; }
    // Hides Animal::clone and keeps the derived type for callers that hold a Dog.
    std::unique_ptr<Dog> clone() const { return std::unique_ptr<Dog>(do_clone()); }

private:
    // Covariant return type: an override may return Dog* where the base returns Animal*.
    Dog* do_clone() const override { return new Dog(*this); }
};

std::vector<std::string> names(const std::vector<const Animal*>& animals) {
    std::vector<std::string> out;
    for (const Animal* a : animals) out.push_back(a->name());
    return out;
}

// Accepts any range whose elements convert to const Animal*, including vector<const Dog*>.
template <std::ranges::input_range R>
    requires std::convertible_to<std::ranges::range_value_t<R>, const Animal*>
std::vector<std::string> names_of(const R& animals) {
    std::vector<std::string> out;
    for (const Animal* a : animals) out.push_back(a->name());
    return out;
}

int main() {
    Dog rex;
    std::vector<const Dog*> dogs{&rex};
    // names(dogs);
    //   error: no matching function for call to 'names'
    // Each template instantiation is an unrelated type: templates are invariant.
    // The iterator-range constructor converts element by element instead.
    std::vector<const Animal*> animals(dogs.begin(), dogs.end());
    std::println("{} {}", names(animals), names_of(dogs));

    std::unique_ptr<Dog> copy = rex.clone();  // Dog::clone keeps the derived type
    std::println("{} {}", copy->name(), copy->bark());
    const Animal& some = rex;
    std::unique_ptr<Animal> base = some.clone();  // through the base: unique_ptr<Animal>
    std::println("{}", base->name());
    // A virtual unique_ptr<Animal> clone() cannot be overridden by unique_ptr<Dog> clone():
    //   error: virtual function 'clone' has a different return type ('unique_ptr<Dog>')
    //   than the function it overrides (which has return type 'unique_ptr<Animal>')
    // Smart pointers convert (unique_ptr<Dog> -> unique_ptr<Animal>), but are not covariant.
}

In practice: instead of std::vector<Base*>, take a template constrained on the element type (std::convertible_to<std::ranges::range_value_t<R>, const Animal*>), as names_of does. For clone with smart pointers, give each class a public non-virtual clone that returns unique_ptr to its own type and calls a private virtual do_clone with a covariant raw-pointer return.

std::unique_ptr<Dog> and std::shared_ptr<Dog> convert to the base pointer type one at a time, but containers of them do not.

Never reinterpret_cast a vector<Derived*> to vector<Base*>: with multiple inheritance the pointer values themselves differ.

std::span<const Animal* const> does not accept a std::vector<const Dog*> either: span needs the element types to match. To keep a non-template function, pass dogs | std::views::transform([](const Dog* d) -> const Animal* { return d; }) to code that takes a range.

Printing a std::vector with std::println needs range formatting: GCC 15+ (libstdc++) or libc++ 17+.

Abstract over containers (higher-kinded types): HKT encodings, GATs, template template parameters

C++

Read a type parameter (Types & syntax) covers parameters that stand for a type such as int; this entry covers parameters that stand for a class template such as std::vector itself, so one function can work over any container. C++ has a real higher-kinded feature: a template template parameter takes a class template, such as std::vector itself, not a type such as std::vector<int>. `template <template <class...> class C, class T, class... Rest>` lets fmap accept any C<T, Rest...> and return C<U> for a new element type, so the same function maps a std::vector or a std::list and returns the same container kind. C++23 std::ranges::to accepts a class template the same way, so `in | std::views::transform(f) | std::ranges::to<C>()` builds C<U> with the element type deduced. The classic use is a class that lets its user pick the storage: Stack<int, std::deque>.

Complete program

Complete program.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cassert>
#include <deque>
#include <list>
#include <print>
#include <ranges>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

// A template template parameter takes a class template such as std::vector itself,
// not a type such as std::vector<int>. This is C++'s closest feature to an HKT.
// Rest... absorbs the allocator, so C<T, Rest...> matches std::vector<int, std::allocator<int>>.
template <template <class...> class C, class T, class... Rest, class F>
auto fmap(const C<T, Rest...>& in, F f) {
    // C++23: ranges::to also takes a class template and deduces the new element type,
    // so the result is C<U> for whatever U the function returns.
    return in | std::views::transform(f) | std::ranges::to<C>();
}

// The classic use: let the caller choose the container a class stores into.
template <class T, template <class...> class Storage = std::vector>
class Stack {
public:
    void push(T v) { items_.push_back(std::move(v)); }
    T pop() {
        T v = std::move(items_.back());
        items_.pop_back();
        return v;
    }
    std::size_t size() const { return items_.size(); }

private:
    Storage<T> items_;
};

int main() {
    std::vector<int> v{1, 2, 3};
    std::list<int> l{4, 5};
    auto dv = fmap(v, [](int n) { return n * 2; });              // std::vector<int>
    auto sl = fmap(l, [](int n) { return std::to_string(n); });  // std::list<std::string>
    static_assert(std::is_same_v<decltype(sl), std::list<std::string>>);
    assert(dv == (std::vector{2, 4, 6}));

    Stack<int> a;              // stores in std::vector<int>
    Stack<int, std::deque> b;  // stores in std::deque<int>
    a.push(1);
    b.push(2);
    b.push(3);
    std::println("{} {} {} {}", dv, sl, a.pop(), b.size());
}

In practice: use a template template parameter when the code must build a container of a different element type from the one it received. When it only reads the container, a plain template parameter constrained with a ranges concept is simpler.

Write template <class...> class C rather than template <class> class C: standard containers have extra defaulted parameters (the allocator), and the variadic form matches all of them.

Containers with non-type template parameters, such as std::array<T, N>, do not match <class...>.

The returned C<U> uses the default allocator for U, not a rebound copy of the input's allocator.

std::ranges::to needs C++23 (libstdc++ 14+, libc++ 17+). Before that, build C<U> out by hand with std::invoke_result_t<F&, const T&> as U and push_back each result.

Printing a std::vector or std::list with std::println needs range formatting: GCC 15+ (libstdc++) or libc++ 17+.