moai-lang-cpp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Quick Reference (30 seconds)

快速参考(30秒)

Modern C++ (C++23/C++20) Development Specialist - RAII, smart pointers, concepts, ranges, modules, and CMake.
Auto-Triggers:
.cpp
,
.hpp
,
.h
,
CMakeLists.txt
,
vcpkg.json
,
conanfile.txt
, modern C++ discussions
Core Capabilities:
  • C++23 Features: std::expected, std::print, std::generator, deducing this
  • C++20 Features: Concepts, Ranges, Modules, Coroutines, std::format
  • Memory Safety: RAII, Rule of 5, smart pointers (unique_ptr, shared_ptr, weak_ptr)
  • STL: Containers, Algorithms, Iterators, std::span, std::string_view
  • Build Systems: CMake 3.28+, FetchContent, presets
  • Concurrency: std::thread, std::jthread, std::async, atomics, std::latch/barrier
  • Testing: Google Test, Catch2
  • Package Management: vcpkg, Conan 2.0
现代C++(C++23/C++20)开发专家 - 涵盖RAII、智能指针、Concepts、Ranges、Modules和CMake。
自动触发场景:
.cpp
,
.hpp
,
.h
,
CMakeLists.txt
,
vcpkg.json
,
conanfile.txt
, 现代C++相关讨论
核心能力:
  • C++23特性:std::expected、std::print、std::generator、deducing this
  • C++20特性:Concepts、Ranges、Modules、Coroutines、std::format
  • 内存安全:RAII、五法则(Rule of 5)、智能指针(unique_ptr、shared_ptr、weak_ptr)
  • STL:容器、算法、迭代器、std::span、std::string_view
  • 构建系统:CMake 3.28+、FetchContent、预设(presets)
  • 并发编程:std::thread、std::jthread、std::async、原子操作、std::latch/barrier
  • 测试:Google Test、Catch2
  • 包管理:vcpkg、Conan 2.0

Quick Patterns

快速模式示例

Smart Pointer Factory Pattern: Create a class with a static factory method that returns std::unique_ptr. Include a header for memory, define a Widget class with a static create method taking an int value parameter. The create method uses std::make_unique to instantiate and return the Widget. The constructor should be explicit and take the value parameter, storing it in a private member variable.
Concepts Constraint Pattern: Define a concept named Numeric that combines std::integral or std::floating_point constraints. Create a template function square that requires T to satisfy the Numeric concept, taking a value parameter and returning value multiplied by itself.
Ranges Pipeline Pattern: Use std::views::iota to create a range from 1 to 100, pipe it through a filter to select even numbers, then transform by squaring each value, and finally take the first 10 results.

智能指针工厂模式:创建一个包含静态工厂方法的类,返回std::unique_ptr。引入内存管理相关头文件,定义Widget类,其静态create方法接收一个int类型的value参数。create方法使用std::make_unique实例化并返回Widget对象。构造函数需声明为explicit,接收value参数并将其存储在私有成员变量中。
Concepts约束模式:定义名为Numeric的Concept,结合std::integral或std::floating_point约束。创建模板函数square,要求类型T满足Numeric Concept,接收value参数并返回value的平方。
Ranges管道模式:使用std::views::iota创建1到100的范围,通过过滤器筛选偶数,然后转换为每个值的平方,最后取前10个结果。

Implementation Guide (5 minutes)

实现指南(5分钟)

C++23 New Features

C++23新特性

std::expected for Error Handling: Create an enum class ParseError with InvalidFormat and OutOfRange values. Define a parse_int function that takes std::string_view and returns std::expected containing either int or ParseError. Inside, use a try-catch block to call std::stoi. Catch std::invalid_argument and return std::unexpected with InvalidFormat, catch std::out_of_range and return std::unexpected with OutOfRange. On success, return the parsed value directly. Usage involves checking the result with if(result) and accessing the value with asterisk operator or handling the error case.
std::print for Type-Safe Output: Include the print header and use std::println for formatted output with curly brace placeholders. Supports format specifiers like colon followed by hash x for hexadecimal or colon followed by .2f for floating point precision.
Deducing This (Explicit Object Parameter): Define a Builder class with a data_ member string. Create a template method append with template parameter Self that takes this Self and and a string_view parameter. Forward self with std::forward and return Self and and. This enables chaining on both lvalue and rvalue objects.
使用std::expected处理错误:创建枚举类ParseError,包含InvalidFormat和OutOfRange两个值。定义parse_int函数,接收std::string_view参数,返回包含int或ParseError的std::expected。函数内部使用try-catch块调用std::stoi。捕获std::invalid_argument异常时,返回携带InvalidFormat的std::unexpected;捕获std::out_of_range异常时,返回携带OutOfRange的std::unexpected。成功解析时直接返回解析后的值。使用时通过if(result)判断结果,通过星号运算符访问值,或处理错误情况。
使用std::print实现类型安全输出:引入print头文件,使用std::println和大括号占位符实现格式化输出。支持格式说明符,如
:x
表示十六进制,
: .2f
表示保留两位小数的浮点数。
Deducing This(显式对象参数):定义Builder类,包含string类型的data_成员。创建模板方法append,模板参数为Self,接收Self类型的this指针和string_view参数。使用std::forward转发self并返回Self对象。这支持在左值和右值对象上进行链式调用。

C++20 Features

C++20特性

Concepts and Constraints: Define a Hashable concept using requires expression that checks if std::hash can produce a std::size_t. Create template functions with requires clauses to constrain Container types to std::ranges::range. Use abbreviated syntax with std::integral auto for simple constraints on individual parameters.
Modules: Create a module interface file with .cppm extension. Use export module followed by the module name. Define an export namespace containing template functions. In consumer files, use import statements instead of include directives. Import std for standard library access in module-aware compilers.
Ranges Library: Define structs for data types like Person with name and age fields. Use pipe operator to chain views::filter with a lambda checking conditions, then views::transform to extract fields. Iterate with range-based for loops. Use std::ranges::sort with projections for sorting by member fields.
Concepts与约束:使用requires表达式定义Hashable Concept,检查std::hash是否能生成std::size_t。创建带有requires子句的模板函数,约束Container类型为std::ranges::range。对单个参数使用缩写语法std::integral auto实现简单约束。
Modules:创建扩展名为.cppm的模块接口文件。使用export module声明模块名称。定义包含模板函数的export命名空间。在消费文件中使用import语句替代include指令。在支持模块的编译器中,使用import std访问标准库。
Ranges库:定义Person等数据类型的结构体,包含name和age字段。使用管道运算符链式调用views::filter(结合lambda表达式检查条件)和views::transform(提取字段)。使用范围for循环迭代。使用带有投影的std::ranges::sort按成员字段排序。

RAII and Resource Management

RAII与资源管理

Rule of Five: Implement a Resource class managing a raw pointer and size. The constructor allocates with new array syntax. The destructor calls delete array. Copy constructor allocates new memory and uses std::copy. Copy assignment uses copy-and-swap idiom by creating a temp and calling swap. Move constructor uses std::exchange to take ownership and null the source. Move assignment deletes current data and uses std::exchange. The swap member swaps both pointer and size members.
Smart Pointer Patterns: For unique ownership, create static factory methods returning std::unique_ptr via std::make_unique. For shared ownership with cycles, use std::enable_shared_from_this as a base class. Store children in std::vector of shared_ptr and parent as std::weak_ptr to break reference cycles. Use weak_from_this when setting parent relationships.
五法则(Rule of Five):实现Resource类管理原始指针和大小。构造函数使用new数组语法分配内存。析构函数调用delete数组。拷贝构造函数分配新内存并使用std::copy。拷贝赋值运算符使用拷贝交换 idiom,创建临时对象并调用swap。移动构造函数使用std::exchange获取所有权并将源对象置空。移动赋值运算符删除当前数据并使用std::exchange。swap成员函数交换指针和大小成员。
智能指针模式:对于独占所有权,创建静态工厂方法,通过std::make_unique返回std::unique_ptr。对于存在循环的共享所有权,使用std::enable_shared_from_this作为基类。将子对象存储在std::vectorstd::shared_ptr中,父对象存储为std::weak_ptr以打破引用循环。设置父关系时使用weak_from_this。

CMake Modern Patterns

CMake现代模式

CMakeLists.txt Structure for C++23: Begin with cmake_minimum_required VERSION 3.28 and project declaration. Set CMAKE_CXX_STANDARD to 23 with STANDARD_REQUIRED ON. Enable CMAKE_EXPORT_COMPILE_COMMANDS. Use generator expressions for compiler-specific warning flags, checking CXX_COMPILER_ID for GNU, Clang, or MSVC. Use FetchContent to declare dependencies with GIT_REPOSITORY and GIT_TAG parameters. Call FetchContent_MakeAvailable to download and configure. Create libraries with add_library, set include directories with target_include_directories, and link with target_link_libraries. For testing, enable_testing, add test executables, link GTest::gtest_main, and use gtest_discover_tests.
C++23项目的CMakeLists.txt结构:以cmake_minimum_required VERSION 3.28和项目声明开头。设置CMAKE_CXX_STANDARD为23,并开启STANDARD_REQUIRED ON。启用CMAKE_EXPORT_COMPILE_COMMANDS。使用生成器表达式设置编译器特定的警告标志,通过检查CXX_COMPILER_ID判断是GNU、Clang还是MSVC。使用FetchContent声明依赖,指定GIT_REPOSITORY和GIT_TAG参数。调用FetchContent_MakeAvailable下载并配置依赖。使用add_library创建库,使用target_include_directories设置包含目录,使用target_link_libraries链接依赖。测试方面,启用enable_testing,添加测试可执行文件,链接GTest::gtest_main,使用gtest_discover_tests发现测试用例。

Concurrency

并发编程

std::jthread and Stop Tokens: Define worker functions taking std::stop_token parameter. Loop while stop_requested returns false, performing work and sleeping. Create std::jthread objects passing the worker function. Call request_stop to signal termination. The thread destructor automatically joins.
Synchronization Primitives: Use std::latch for one-time synchronization by calling count_down. Use std::barrier for repeated synchronization with arrive_and_wait. Use std::counting_semaphore for resource pools with acquire and release calls.

std::jthread与停止令牌:定义接收std::stop_token参数的工作函数。在stop_requested返回false时循环执行任务并休眠。创建std::jthread对象并传入工作函数。调用request_stop发送终止信号。线程析构函数会自动执行join操作。
同步原语:使用std::latch实现一次性同步,调用count_down。使用std::barrier实现重复同步,调用arrive_and_wait。使用std::counting_semaphore实现资源池,调用acquire和release。

Advanced Implementation (10+ minutes)

高级实现(10分钟以上)

For comprehensive coverage including:
  • Template metaprogramming patterns
  • Advanced concurrency (thread pools, lock-free data structures)
  • Memory management and custom allocators
  • Performance optimization (SIMD, cache-friendly patterns)
  • Production patterns (dependency injection, factories)
  • Extended testing with Google Test and Catch2
See:
  • Advanced Patterns - Complete advanced patterns guide

如需全面了解以下内容:
  • 模板元编程模式
  • 高级并发(线程池、无锁数据结构)
  • 内存管理与自定义分配器
  • 性能优化(SIMD、缓存友好模式)
  • 生产级模式(依赖注入、工厂模式)
  • Google Test与Catch2扩展测试
请参考:
  • 高级模式 - 完整的高级模式指南

Context7 Library Mappings

Context7库映射

  • /microsoft/vcpkg - Package manager
  • /conan-io/conan - Conan package manager
  • /google/googletest - Google Test framework
  • /catchorg/Catch2 - Catch2 testing framework
  • /fmtlib/fmt - fmt formatting library
  • /nlohmann/json - JSON for Modern C++
  • /gabime/spdlog - Fast logging library

  • /microsoft/vcpkg - 包管理器
  • /conan-io/conan - Conan包管理器
  • /google/googletest - Google Test测试框架
  • /catchorg/Catch2 - Catch2测试框架
  • /fmtlib/fmt - fmt格式化库
  • /nlohmann/json - JSON for Modern C++
  • /gabime/spdlog - 快速日志库

Works Well With

协同工具

  • moai-lang-rust
    - Systems programming comparison and interop
  • moai-domain-backend
    - Backend service architecture
  • moai-workflow-testing
    - DDD and testing strategies
  • moai-essentials-debug
    - Debugging and profiling
  • moai-foundation-quality
    - TRUST 5 quality principles

  • moai-lang-rust
    - 系统编程对比与互操作
  • moai-domain-backend
    - 后端服务架构
  • moai-workflow-testing
    - 领域驱动设计与测试策略
  • moai-essentials-debug
    - 调试与性能分析
  • moai-foundation-quality
    - TRUST 5质量原则

Troubleshooting

故障排查

Version Check: Run g++ --version to verify GCC 13+ for C++23 support, clang++ --version for Clang 17+, and cmake --version for CMake 3.28+.
Common Compilation Flags: Use -std=c++23 with -Wall -Wextra -Wpedantic -O2 for standard builds. Add -fsanitize=adddess,undefined -g for debugging builds.
vcpkg Integration: Clone the vcpkg repository from GitHub, run bootstrap-vcpkg.sh, then install packages like fmt, nlohmann-json, and gtest using vcpkg install. Configure CMake with -DCMAKE_TOOLCHAIN_FILE pointing to vcpkg's buildsystems/vcpkg.cmake.

Last Updated: 2026-01-11 Status: Active (v1.1.0)
版本检查:运行g++ --version验证GCC 13+以支持C++23,运行clang++ --version验证Clang 17+,运行cmake --version验证CMake 3.28+。
常用编译标志:标准构建使用-std=c++23 -Wall -Wextra -Wpedantic -O2。调试构建添加-fsanitize=address,undefined -g。
vcpkg集成:从GitHub克隆vcpkg仓库,运行bootstrap-vcpkg.sh,然后使用vcpkg install安装fmt、nlohmann-json、gtest等包。配置CMake时指定-DCMAKE_TOOLCHAIN_FILE指向vcpkg的buildsystems/vcpkg.cmake。

最后更新:2026-01-11 状态:活跃(v1.1.0)