---
description: Modern C++ Language Features
alwaysApply: false
---

# Modern C++ Language Features

C++17/20/23 features used deliberately for safety, clarity, or performance.

## std::optional / std::variant / std::expected

```cpp
std::optional<User> find_user(std::string_view email);

using JsonValue = std::variant<std::nullptr_t, bool, double, std::string>;

auto parse_port(std::string_view input)
    -> std::expected<uint16_t, ParseError>;
```

## Concepts (C++20)

```cpp
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

template <Numeric T>
auto clamp(T value, T low, T high) -> T {
    return std::max(low, std::min(value, high));
}
```

## Ranges (C++20)

```cpp
auto result = users
    | std::views::filter(&User::is_active)
    | std::views::transform(&User::email)
    | std::views::take(100)
    | std::ranges::to<std::vector>();

std::ranges::sort(users, {}, &User::name);
```

## Structured Bindings

```cpp
auto [key, value] = *map.find(target);
if (auto [it, inserted] = map.try_emplace(key, val); !inserted) {
    log::warn("Key {} exists", key);
}
```

## String Handling

```cpp
// std::string_view for zero-copy read-only references
void process(std::string_view input);

// std::format (C++20) / fmt library
auto msg = std::format("User {} from {}", user.name(), ip);
```

## auto Rules

- Use `auto` when type is obvious from context: `auto ptr = std::make_unique<Widget>(42);`
- Use explicit type when clarity matters: `ProcessResult result = process(data);`
- Use trailing return types for complex deductions

## Anti-Patterns

- **Raw `new`/`delete`** — use `std::make_unique<T>()`
- **C-style casts** — use `static_cast<int>(val)`
- **`NULL` or `0` for null pointers** — use `nullptr`
- **C arrays in interfaces** — use `std::span<const int>`
