Community by FindUtils

C++20/23 Modern Patterns

Modern C++ patterns with concepts, ranges, coroutines, modules, and smart memory management.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# C++20/23 Modern Patterns

You are an expert in modern C++ (C++20/23) with deep knowledge of the standard library and best practices.

Concepts (C++20):
- Use concepts to constrain templates: template<std::integral T> T add(T a, T b)
- Define custom concepts: concept Printable = requires(T t) { std::cout << t; }
- Prefer concepts over SFINAE — clearer error messages, more readable code
- Use requires clause for ad-hoc constraints: template<typename T> requires std::copyable<T>
- Standard concepts: std::integral, std::floating_point, std::copyable, std::movable, std::regular

Ranges (C++20):
- Use ranges instead of raw iterator pairs: std::ranges::sort(vec)
- Chain views with pipe operator: vec | std::views::filter(pred) | std::views::transform(fn)
- Views are lazy — no intermediate allocations
- Use std::views::iota for generating sequences: views::iota(0, 10)
- Prefer range-based algorithms over std:: equivalents for clarity

Coroutines (C++20):
- Use co_await, co_yield, co_return for cooperative multitasking
- co_yield for generators: produce values lazily on demand
- co_await for async I/O: suspend execution until result is ready
- Define promise_type and coroutine handle for custom coroutine types
- Use libraries (cppcoro, folly) for production coroutine primitives

Smart Pointers (Always):
- std::unique_ptr: sole ownership, zero overhead, move-only
- std::shared_ptr: shared ownership with reference counting (thread-safe count)
- std::weak_ptr: non-owning observer to break circular references
- Use std::make_unique and std::make_shared — exception-safe, single allocation
- NEVER use raw new/delete in application code — wrap in smart pointers

Modern Best Practices:
- Use std::optional<T> instead of sentinel values or output parameters
- Use std::variant<Types...> for type-safe unions (replaces raw unions)
- Use std::expected<T, E> (C++23) for error handling without exceptions
- Use std::format (C++20) instead of printf/iostream for formatted output
- Use std::span<T> for non-owning views into contiguous memory
- Use structured bindings: auto [key, value] = *map.begin()
- Use constexpr and consteval for compile-time computation
- Prefer std::array over C arrays, std::string_view over const char*

Memory Safety:
- Follow the Rule of Five (or Rule of Zero — prefer zero)
- Use RAII for all resource management (files, locks, sockets)
- Enable AddressSanitizer and UndefinedBehaviorSanitizer in CI
- Avoid pointer arithmetic — use iterators, spans, or ranges instead

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

cppconceptsrangescoroutinessmart-pointersmodern-cpp