/cpp:codingfrom cpp
Use when writing or reviewing C++ or Objective-C++, covering functional design with value types and results, ownership, coroutines, compile-time evaluation, memory layout, concurrency, and C interfaces
Ships in cpp. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Covers C++ and Objective-C++ design from signature shape to C boundaries, with the standard library as vocabulary and a package for each member the library lacks.
[REFERENCES]:
visit, bindings, and recursionstdexecFunction signatures are contracts: parameter types describe every value a function accepts, and its return type every outcome its caller handles. Callables take the form their use states:
| [INDEX] | [USE] | [FORM] |
|---|---|---|
| [01] | Called before return | Template parameter constrained by std::invocable, std::predicate |
| [02] | Called before return, body in a source unit | std::function_ref<R(Args...)>, or its package |
| [03] | Stored beside callables of other types | std::function<R(Args...)> in one member or container |
| [04] | Stored by a consumer that can be a template | Type parameter of its owner |
| [05] | Chosen at compile time | Template constrained by a concept |
| [06] | Arriving at run time | Interface of pure virtual members behind std::unique_ptr |
| [07] | Leading arguments fixed | std::bind_front, lambda capturing by value |
| [08] | Crossing a C interface | Function pointer beside a void* context |
std::bind_front specializes them at a composition rootstd::pair and std::tuple stay out of signatures[[nodiscard]] on its class or through bugprone-unused-return-valuereferences/functions.md for combinators, functions as data, adapters, dispatch, and the composition rootFunctions honor their signature when each declared input yields a declared output, with no exception, sentinel, or output parameter as an outcome the signature omits:
std::uint32_t -> Extent is dishonest where zero fails, and std::expected<Extent, Error> as its return states every outcomestd::optional or std::optional<T&>, never -1, nullptr, npos, zero, or an empty string standing for itT& parameter changes a caller's object in place alonestd::expected<void, E>, and void stays on an effect that cannot failT* stays at a C interface, and signatures elsewhere take views, borrows, or ownersFunctions are pure when their result depends on their arguments alone and evaluation changes nothing outside them, and a pure call's result replaces the call. Side effects are writes to members, statics, or globals, writes through a reference parameter, I/O, and reads of ambient input:
std::getenv, std::random_device, global locale, working directory) are read at a composition root and passedstatic state, mutable lambdas, and namespace-scope objects with dynamic initialization or exit-time destruction stay outHigher-order functions own stable control flow and their caller supplies the varying rule: std::ranges::count_if owns iteration and its predicate owns inclusion, std::optional::or_else owns absence and its callable owns the fallback. Call sites select the form:
std::bind_front specialization where it shortens every call sitestd::array of function pointers where behaviors share a signature and vary as datastd::ranges::all_of, any_of, or none_of where a short-circuiting boolean answersExpressions evaluate to values and statements perform effects: a loop whose body performs an effect per element stays a statement, and a choice between values is an expression. Values are built in one expression naming each field at creation:
const auto, a type spelled where an initializer leaves its width or signedness unstated?: for ordered cases, or a switch inside a lambda called in placedefault, so an added enumerator fails the buildvisit over one overload per alternative, and std::get and std::get_if stay out_ fields it discards, and a binding in an if condition tests its objectstd::format call, never fragments joinedreferences/expressions.md for initialization, switches, visit, bindings, and recursionRecursive functions need a base case returning the final value, a recursive case moving closer to it, and a return on every path. Depth and successor sharing select the form:
| [INDEX] | [APPROACH] | [USE_WHEN] | [COST] |
|---|---|---|---|
| [01] | Direct recursion | Depth small and bounded by data shape | Unbounded depth grows the stack |
| [02] | [[clang::musttail]] return f(...) | Tail call, unbounded depth | Caller and callee signatures match |
| [03] | Loop over a std::vector stack | Non-tail recursion, unbounded depth | Frames become heap entries |
| [04] | Fold over a sequence | One state threaded over elements | Intermediate states are discarded |
| [05] | Loop collecting a local | Intermediate states a reader consumes | Bound in the loop's condition |
| [06] | Walk with a visited set | Shared or cyclic successors | Graph built before the walk |
Each state a consumer inspects is one alternative, and a constructor or factory is the only path to a value:
| [INDEX] | [CONCERN] | [TYPE] |
|---|---|---|
| [01] | Closed set of labels | enum class over the narrowest underlying type its values fit |
| [02] | Closed set of cases with data | std::variant of aggregates |
| [03] | Value with an invariant | Class with a private constructor and an expected factory |
| [04] | Literal with an invariant | consteval constructor |
| [05] | Record without an invariant | Aggregate with public fields, designated initializers |
| [06] | Quantities sharing a representation | Tagged wrapper per meaning, or a unit type |
| [07] | Duration or instant | std::chrono duration, time_point of steady_clock for an interval |
| [08] | Owned resource | Standard owner, else a move-only class releasing once |
| [09] | History or snapshot shared across threads | std::shared_ptr<const T>, or a persistent structure |
std::optional, and a state no consumer reads leaves the typeinit or setter sequence followsstd::exchange= delete("<reason>")struct holds fields no rule relates, class holds an invariant its private fields keepstatic_assert beside the typeenum stays inside extern "C", and type tests (dynamic_cast, typeid, std::is_same_v branches) become an overload of a visitreferences/types.md for each formValues are const once built, and a change builds a successor from an old value and the information the change needs:
const, as a const member deletes assignment, and immutability comes from const objects and functions returning successorsconst reaches the object alone: a pointer, std::span, or std::shared_ptr<T> member leaves its target writablestd::shared_ptr<const T>, swapped under a mutex or held in a persistent structurereferences/immutable-data.md for snapshots, values and entities, shared versions, and persistent structuresSignatures state what a function does with each argument:
| [INDEX] | [USE] | [PARAMETER] |
|---|---|---|
| [01] | Read | const T&, by value for a trivially copyable type of 2 pointers or less |
| [02] | Read a sequence, text, or grid | std::span<const T>, std::string_view, std::mdspan |
| [03] | Kept in a new object, move cheap | By value, moved once into place |
| [04] | Kept in an existing object, or move copies | const T&, with a T&& overload where a caller's temporary pays for it |
| [05] | Changed in place | T& |
| [06] | Absent or present borrow | std::optional<T&> |
| [07] | Forwarded by generic code | T&& with std::forward |
Stored relations take the type naming them:
| [INDEX] | [RELATION] | [TYPE] |
|---|---|---|
| [01] | Sole owner | Value member, std::unique_ptr for an incomplete or virtual type |
| [02] | Owners with unrelated lifetimes | std::shared_ptr<const T> |
| [03] | C handle | std::unique_ptr<T, Deleter>, filled through std::out_ptr |
| [04] | Element of a pool reusing its slots | Index with a generation |
| [05] | Borrow in a class deleting copy and move | T& member |
| [06] | Borrow in a copyable holder | std::reference_wrapper<T>, std::span, std::string_view |
| [07] | Borrow a holder's move detaches | std::optional<T&>, emptied by the move |
std::span, std::string_view, std::mdspan, std::optional<T&>)[[clang::lifetimebound]], one explicit object parameter serving const and mutable objects-Wlifetime-safety of LLVM's clang reports a borrow outliving its owner, a container changed while a view of it is read, and a view of a local returned[&] staying for a lambda called before its scope endsconst T&, as a std::shared_ptr copy is an atomic increment per callstd::unique_ptr::release at the call handing them over, and new appears nowhere elsereferences/ownership.md for borrowing members, optional borrows, stored borrows, captures, and arenasEvery fallible function returns an outcome type, and one type serves one concern:
| [INDEX] | [TYPE] | [CONCERN] |
|---|---|---|
| [01] | std::optional<T> | Absence without a reason |
| [02] | std::optional<T&> | Borrow a lookup can miss |
| [03] | std::expected<T, E> | One failure a caller branches on |
| [04] | std::expected<void, E> | Effect that reports failure and returns no value |
| [05] | std::expected<T, std::vector<E>> | Every failure of independent checks |
Dependent steps bind and stop at their first failure, and independent checks all run and return every failure:
| [INDEX] | [STEP] | [MEMBER] |
|---|---|---|
| [01] | T -> U | transform |
| [02] | T -> expected<U, E> | and_then |
| [03] | E -> F | transform_error |
| [04] | E -> expected<T, F> | or_else |
| [05] | Value at the composition root | value_or, error_or |
#include <charconv>
#include <cstdint>
#include <expected>
#include <memory>
#include <string_view>
#include <system_error>
namespace imaging {
enum class Error : std::uint8_t {
Malformed,
OutOfRange,
};
constexpr auto parse_size(std::string_view text) noexcept -> std::expected<std::uint32_t, Error> {
std::uint32_t size{};
const auto [end, code] = std::from_chars(std::to_address(text.begin()), std::to_address(text.end()), size);
return code == std::errc::result_out_of_range ? std::unexpected{Error::OutOfRange}
: code != std::errc{} || end != std::to_address(text.end()) ? std::unexpected{Error::Malformed}
: std::expected<std::uint32_t, Error>{size};
}
constexpr auto validate_size(std::uint32_t size) noexcept -> std::expected<std::uint32_t, Error> {
return size >= 2 && size <= 256 ? std::expected<std::uint32_t, Error>{size} : std::unexpected{Error::OutOfRange};
}
constexpr auto lattice_samples(std::string_view text) noexcept -> std::expected<std::uint64_t, Error> {
return parse_size(text).and_then(validate_size).transform([](std::uint32_t size) { return std::uint64_t{size} * size * size; });
}
static_assert(lattice_samples("33").value_or(0) == 35'937 && !lattice_samples("1") && !lattice_samples("3x"));
}
lattice_samples counts the samples a Cube LUT's LUT_3D_SIZE value declares. parse_size keeps a number past std::uint32_t apart from malformed text through the ec of std::from_chars, validate_size binds on a parsed size alone, and transform cubes it in std::uint64_t. Each step stays inside std::expected, as an unwrap followed by a rewrap restates its failure handling.
Error types follow how their callers respond:
| [INDEX] | [FORM] | [FITS] | [COST] |
|---|---|---|---|
| [01] | Enumeration per package | Failures a boundary maps onto one code set | Callers handle cases a function never returns |
| [02] | Enumeration per operation family | Failures differing by operation | transform_error at each composition |
| [03] | std::variant of error types | Failures holding different data | Visit at the root, wide error types |
| [04] | std::error_code | Failure crossing an OS or library boundary | Category per library |
std::formatter per error type derives its text from label and fields, and a call site formats the value alonestd::error_code, compared against std::errc where a caller branchesstd::expectedthrow and members reporting by throwing (at, value, std::stoi) stay out of every unitnoexcept states a fact about every callee, and an exception leaving a noexcept function ends the processreferences/results.md for validation, workflows, accumulation, messages, entry points, and defectsExpected failures are values, and a defect is a state its caller cannot act on (a precondition its caller's bug alone violates, a broken invariant, an enumeration past its cases):
__builtin_verbose_trap("<package>", "<message>"), constant text a debugger and a crash report showstd::abort after writing its message, as the runtime resumes a trap foreverstd::expectedthrow fails to compile where exceptions are off| [INDEX] | [WRONG_FORM] | [CORRECT_FORM] |
|---|---|---|
| [01] | has_value() test, then *result, between pipeline steps | transform, and_then, one test at an entry |
| [02] | if (!step) return std::unexpected{step.error()}; per step | and_then chain |
| [03] | bool return beside an output parameter | std::expected<T, E> |
| [04] | value_or with an arbitrary default hiding absence | std::expected naming the error |
| [05] | Message text built at the failing call | Error value, text from its std::formatter |
| [06] | Separate result and error fields, or a default on failure | One std::expected |
| [07] | Fields meaningful together under one flag | std::optional of an aggregate, or a variant |
| [08] | Error code compared against an integer or message text | std::errc or the error enumerator |
| [09] | std::expected of a failure no caller can act on | Trap naming the defect |
| [10] | assert, std::terminate, or abort with no message for a defect | Trap naming the defect, in every build |
| [11] | catch in main returning a status with no text | what() printed, then the status |
Entry points (main, a C entry, a host callback) test an outcome once and read *result or error() to translate it to their caller's vocabulary, as imperative code at the boundary.
Programs keep I/O at a small boundary around a pure core: each decision is a pure function, and a C entry, composition root, or host callback performs the effects it returns:
const&dlsym, NSClassFromString, NSSelectorFromString)references/effects.md for isolation, injection, scopes, and the form of deferred workreferences/senders.md for deferral, environments, scopes, policies, and agents through stdexecreferences/state.md for transitions, caches, callback owners, event sourcing, and loopsCoroutine frames outlive the call that made them, so nothing a frame reads belongs to its caller:
this auto), which copies the closure into the framestd::expected, and no exception leaves a framereferences/coroutines.md for tasks, captures, suspension points, and generatorsContainers follow their most frequent operation:
| [INDEX] | [OPERATION] | [CONTAINER] |
|---|---|---|
| [01] | Ordered reads, appends | std::vector, reserved once at a known count |
| [02] | Count fixed at compile time | std::array |
| [03] | Keyed lookups, read more than written | std::flat_map, std::flat_set |
| [04] | Keyed lookups under steady insert or erase | std::unordered_map, std::map where key order is read |
| [05] | Lookups a measurement names | Open addressing (ankerl::unordered_dense, boost::unordered) |
| [06] | Constant lookups | Sorted constexpr std::array, std::ranges::equal_range |
| [07] | Insertion and removal at both ends | std::deque |
| [08] | Grid, or fixed-width chunks of a buffer | One std::vector under a std::mdspan |
std::ranges::to collects, as a collection between stages is a second passmax, count_if, any_of, contains), and fold_left where no member names one and its accumulator is trivially copyablezip, neighbors from pairwise or adjacent, and runs of one key from chunk_bystd::equal_to<>, and a std::string_view finds without allocatingstd::views::as_rvaluefor over a range stays where its body performs an effect per elementreferences/sequences.md for projections, reductions, orders, pipelines, positions, and movesCode a measurement names changes in order: remove work, copies, and allocations, densify layout, fuse passes, then widen to more threads:
std::pmr::memory_resource parameter where their caller picks the source of temporary storageresize_and_overwrite, which writes no zero fillstd::format_to_n into caller storage and parses through std::from_chars[[gnu::cold]] function the path callsstd::span, never one element per callalignas(std::hardware_destructive_interference_size), a layout kept off every C interface-Wunsafe-buffer-usage, and a hardened library traps an index past a std::spanstd::bit_cast and std::as_bytes, wire order through std::byteswap against std::endianreferences/memory.md for measurement, layout, columns, handles, buffers, kernels, lanes, and byte formatsShared state has one owner, and work has a scope that joins it:
std::mutex are one type, each field marked __attribute__((guarded_by(mutex_))), and -Wthread-safety proves each access__attribute__((locks_excluded(mutex_))), so a call made while holding it is a findingstd::atomic<T>::wait on an epoch each wake source advances, and writers notify after their storestd::condition_variable_any over an annotated guard, its stop token waking it__attribute__((requires_capability(mutex_))) after a lambda's captures, so -Wthread-safety reads each guarded fieldstd::jthread member declared after the state it reads, taking a std::stop_tokenstd::atomicrelaxed where a value publishes no other data, release with acquire where it does, seq_cst for one shared ordernoexcept [[clang::nonblocking]], as -Wfunction-effects reports each send, lock, or allocationreferences/concurrency.md for parallel loops, guarded state, workers, deadlines, and atomicsFunctions a constant expression can evaluate are constexpr, and a value that must exist before run time comes from consteval:
requires expression can readconstexpr values built by a lambda called in placeconstexpr, constinit where they changereferences/compile-time.md for checked literals, computed tables, constraints, and packsValues take the type stating their meaning, decoded once where they enter:
| [INDEX] | [VALUE] | [TYPE] |
|---|---|---|
| [01] | Quantity | Unit type (mp-units), or an aggregate with the operations it allows |
| [02] | Instant or date | std::chrono sys_time, sys_days, steady_clock for an interval |
| [03] | Identifier | Distinct type over its bytes, compared bytewise |
| [04] | Text | std::string in UTF-8, std::string_view borrowed |
| [05] | Decimal amount | Decimal type (boost-decimal), never binary floating point |
| [06] | Path, version | std::filesystem::path, parsed version type |
| [07] | Size | std::size_t for storage, std::uint64_t for a file or wire size |
std::string::c_str()), as a std::string_view states nonestd::format without L) and is never compared or parsed back<cctype> reads one byte in one localeNumeric facts come from the package or standard header that states them:
| [INDEX] | [FACT] | [MEMBER] |
|---|---|---|
| [01] | Constant | <numbers> (std::numbers::pi_v<T>) |
| [02] | Linear algebra | Eigen, or the platform's BLAS and LAPACK |
| [03] | Special function, root | boost-math |
| [04] | Transform | fftw3, or the platform's FFT |
| [05] | Arbitrary precision | boost-multiprecision |
| [06] | Geometric predicate | CGAL |
| [07] | Bit work | <bit> (std::bit_ceil, std::countr_zero) |
| [08] | Interpolation, distance | std::lerp, std::midpoint, std::hypot |
| [09] | Small difference | std::expm1, std::log1p |
| [10] | Overflow, narrowing, sign | ckd_add, ckd_sub, ckd_mul, std::in_range, std::cmp_less |
max(absolute, relative * max(abs(a), abs(b))) of caller tolerances, as an absolute bound alone fails at large magnitudes and a relative one at zero== on computed floating-point values is a finding (-Wfloat-equal), and ULP distances stay in testsexpm1)std::fma fuses everywhere, and -ffp-contract decides a * b + c per target and build-ffast-math stays off where code reads NaN, infinity, or signed zero, or relies on source order of a sumreferences/memory.md for checked arithmetic and byte orderHeaders are self-contained, and named modules build where every toolchain of their consumers scans them. Each kind of module unit has one job:
| [INDEX] | [UNIT] | [DECLARATION] | [HOLDS] |
|---|---|---|---|
| [01] | Primary interface | export module m; | export import :part; for every interface partition |
| [02] | Interface partition | export module m:part; | Exported declarations of one concept |
| [03] | Internal partition | module m:part; | Declarations units of m import and no consumer sees |
| [04] | Implementation unit | module m; | Definitions of functions an interface declares |
| [05] | Global module fragment | module; then #include | Every header: other packages' and C |
inline, constexpr, consteval, templates, or members, and headers hold no anonymous namespacereferences/modules.md for headers, each unit, and the global module fragmentC interfaces are plain C headers a binding generator and each unit of the library parse alike, with no C++ type, and every entry of one library takes the same form per decision:
noexcept, and no C++ or Objective-C exception crosses an entryreferences/c-abi.md for the choices with their tradeoffs and the decisions a design answersCompilers, libraries, and hosts decide which members code can name:
references/current-forms.md states each member's librariesreferences/current-forms.md for current forms, library differences, C++20 forms, and packages for absent membersreferences/platforms.md for toolchains and hostsObjective-C++ units build under ARC (-fobjc-arc), follow every rule above, and hold Objective-C objects in C++ types:
__weak members, which read nil once that owner ends, loaded once into a strong local per scopeCreate or Copy function enter ARC through CFBridgingRelease.mm unit holds them@autoreleasepool-Wcompletion-handler)@throw and @try stay out, as Objective-C exceptions are programmer errors, and an NSError** result decodes into std::expected at its callreferences/attributes.md (opens in a new tab)references/c-abi.md (opens in a new tab)references/checks.md (opens in a new tab)references/compile-time.md (opens in a new tab)references/concurrency.md (opens in a new tab)references/coroutines.md (opens in a new tab)references/current-forms.md (opens in a new tab)references/effects.md (opens in a new tab)references/expressions.md (opens in a new tab)references/functions.md (opens in a new tab)references/immutable-data.md (opens in a new tab)references/language-features.md (opens in a new tab)references/memory.md (opens in a new tab)references/modules.md (opens in a new tab)references/ownership.md (opens in a new tab)references/platforms.md (opens in a new tab)references/results.md (opens in a new tab)references/senders.md (opens in a new tab)references/sequences.md (opens in a new tab)references/state.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub bsamiee/rasm --plugin cpp3 skills in this plugin
/debuggingUse when C, C++, or Objective-C misbehaves at run time and its cause is unproven (wrong value, failing test case, throw, trap, sanitizer report, crash core), covering build facts, test launches, value reads under lldb-dap, exception and trap stops, dSYMs, core files, attaches, and sanitizer builds/unrealUse when writing code an Unreal Engine module or a package it links compiles, or debugging, rebuilding, or reloading C++, Python, or Blueprint running inside Unreal Engine on macOS, or reading its logs, crash reports, and traces, covering module build rules, editor attaches, native stops, Hot Reload, embedded Python, and Blueprint limitsOther plugins' skills for the same job