alexandrescu-modern-cpp-design

Write C++ code following Andrei Alexandrescu's Modern C++ Design principles. Emphasizes policy-based design, template metaprogramming, and type-safe generic abstractions. Use when designing flexible, reusable libraries or when compile-time computation beats runtime overhead.

16 stars

Best use case

alexandrescu-modern-cpp-design is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Write C++ code following Andrei Alexandrescu's Modern C++ Design principles. Emphasizes policy-based design, template metaprogramming, and type-safe generic abstractions. Use when designing flexible, reusable libraries or when compile-time computation beats runtime overhead.

Teams using alexandrescu-modern-cpp-design should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/alexandrescu-modern-cpp-design/SKILL.md --create-dirs "https://raw.githubusercontent.com/diegosouzapw/awesome-omni-skill/main/skills/development/alexandrescu-modern-cpp-design/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/alexandrescu-modern-cpp-design/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How alexandrescu-modern-cpp-design Compares

Feature / Agentalexandrescu-modern-cpp-designStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Write C++ code following Andrei Alexandrescu's Modern C++ Design principles. Emphasizes policy-based design, template metaprogramming, and type-safe generic abstractions. Use when designing flexible, reusable libraries or when compile-time computation beats runtime overhead.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Andrei Alexandrescu Style Guide

## Overview

Andrei Alexandrescu's "Modern C++ Design" revolutionized how we think about C++ templates. His work on Loki library and policy-based design showed that templates are not just for containers—they're a compile-time programming language.

## Core Philosophy

> "C++ templates are Turing-complete. Use this power wisely."

> "Policy-based design: assemble types from interchangeable parts."

Alexandrescu believes in **pushing computation to compile time** and **using the type system as a design tool**, not just a safety mechanism.

## Design Principles

1. **Policy-Based Design**: Build classes from interchangeable policy classes that customize behavior without inheritance overhead.

2. **Compile-Time over Runtime**: What can be computed at compile time should be.

3. **Type Lists and Metaprogramming**: Types themselves become first-class citizens that can be manipulated.

4. **Design Patterns in Types**: Classic GoF patterns implemented with zero runtime overhead.

## When Writing Code

### Always

- Consider if behavior can be a compile-time policy
- Use `static_assert` to document and enforce requirements
- Prefer tag dispatching over runtime branching for type-based logic
- Make templates SFINAE-friendly (C++11/14) or use concepts (C++20)
- Document template requirements explicitly

### Never

- Use runtime polymorphism when static polymorphism suffices
- Write duplicate code that differs only in types
- Ignore compile-time computation opportunities
- Leave template errors to become cryptic instantiation failures

### Prefer

- Policy classes over strategy pattern (no vtable)
- Type traits over runtime type checking
- `constexpr` functions over template metafunctions (modern C++)
- Concepts over SFINAE (C++20)
- Variadic templates over recursive type lists (modern C++)

## Code Patterns

### Policy-Based Design

```cpp
// Traditional OOP: Runtime overhead, fixed at compile time anyway
class Widget : public ICreationPolicy, public IThreadingPolicy { /* ... */ };

// Policy-Based: Zero overhead, infinitely configurable
template <
    class CreationPolicy,
    class ThreadingPolicy = SingleThreaded,
    class CheckingPolicy = NoChecking
>
class SmartPtr : public CreationPolicy, 
                 public ThreadingPolicy,
                 public CheckingPolicy {
    // Policies are mixed in, no vtable
};

// Usage: Configure at compile time
using ThreadSafePtr = SmartPtr<HeapCreation, MultiThreaded, AssertCheck>;
using FastPtr = SmartPtr<HeapCreation, SingleThreaded, NoChecking>;

// Policies are just classes with required interface
struct HeapCreation {
    template<class T>
    static T* Create() { return new T; }
    
    template<class T>
    static void Destroy(T* p) { delete p; }
};

struct SingleThreaded {
    struct Lock {
        Lock() = default;  // No-op
    };
};

struct MultiThreaded {
    struct Lock {
        Lock() { /* acquire mutex */ }
        ~Lock() { /* release mutex */ }
    };
};
```

### Type Traits and SFINAE

```cpp
// Type trait: Does T have a serialize() method?
template<typename T, typename = void>
struct has_serialize : std::false_type {};

template<typename T>
struct has_serialize<T, 
    std::void_t<decltype(std::declval<T>().serialize())>
> : std::true_type {};

// Use it for conditional behavior
template<typename T>
auto save(const T& obj) -> std::enable_if_t<has_serialize<T>::value> {
    obj.serialize();
}

template<typename T>
auto save(const T& obj) -> std::enable_if_t<!has_serialize<T>::value> {
    default_serialize(obj);
}

// C++20: Much cleaner with concepts
template<typename T>
concept Serializable = requires(T t) {
    { t.serialize() } -> std::convertible_to<std::string>;
};

void save(Serializable auto const& obj) {
    obj.serialize();
}
```

### Compile-Time Type Lists (Classic Alexandrescu)

```cpp
// Type list: A compile-time list of types
template<typename... Ts>
struct TypeList {};

// Operations on type lists
template<typename List>
struct Length;

template<typename... Ts>
struct Length<TypeList<Ts...>> {
    static constexpr size_t value = sizeof...(Ts);
};

// Get type at index
template<size_t I, typename List>
struct TypeAt;

template<typename Head, typename... Tail>
struct TypeAt<0, TypeList<Head, Tail...>> {
    using type = Head;
};

template<size_t I, typename Head, typename... Tail>
struct TypeAt<I, TypeList<Head, Tail...>> {
    using type = typename TypeAt<I - 1, TypeList<Tail...>>::type;
};

// Usage
using MyTypes = TypeList<int, double, std::string>;
static_assert(Length<MyTypes>::value == 3);
using Second = TypeAt<1, MyTypes>::type;  // double
```

### Visitor Pattern via Templates

```cpp
// Traditional visitor: Virtual dispatch at every node
// Alexandrescu approach: Static visitor with type list

template<typename... Types>
class Variant;

template<typename Visitor, typename Variant>
auto visit(Visitor&& v, Variant&& var) {
    return var.visit(std::forward<Visitor>(v));
}

// Modern C++ (std::variant does this)
using Value = std::variant<int, double, std::string>;

auto result = std::visit(overloaded{
    [](int i) { return std::to_string(i); },
    [](double d) { return std::to_string(d); },
    [](const std::string& s) { return s; }
}, value);

// The 'overloaded' helper (Alexandrescu-style)
template<class... Ts> 
struct overloaded : Ts... { 
    using Ts::operator()...; 
};
template<class... Ts> 
overloaded(Ts...) -> overloaded<Ts...>;
```

## Mental Model

Alexandrescu thinks of C++ templates as a **compile-time functional language**:

1. **Types as values**: Types can be computed, stored, and transformed
2. **Templates as functions**: Template instantiation is function application
3. **Specialization as pattern matching**: Like case statements on types
4. **Recursion for iteration**: Compile-time loops via recursive templates

## The D Language Connection

Alexandrescu later co-designed D, which incorporates many C++ template lessons:
- Built-in compile-time function execution
- String mixins for code generation
- Better error messages for templates

These ideas now appear in modern C++ (`constexpr`, `if constexpr`, concepts).

## When to Apply

Use Alexandrescu's techniques when:
- You need maximum performance (zero runtime overhead)
- Behavior variations are known at compile time
- You're building a library with many configuration options
- Type-based dispatch is frequent

Avoid when:
- Runtime polymorphism is genuinely needed
- Compile times are already problematic
- Team isn't comfortable with template metaprogramming

Related Skills

adw-design

16
from diegosouzapw/awesome-omni-skill

Guide creation of AI Developer Workflows (ADWs) that combine deterministic orchestration code with non-deterministic agents. Use when building automated development pipelines, designing AFK agent systems, or implementing the PITER framework.

Advanced Modular Library Design

16
from diegosouzapw/awesome-omni-skill

Design modular libraries with clear package boundaries, feature-first organization, and clean API surfaces. Use when structuring monorepos, defining module boundaries, or designing library APIs.

action-mapping-designer

16
from diegosouzapw/awesome-omni-skill

This skill should be used when ensuring training focuses on performance outcomes and business impact. Use this skill to identify essential content, design performance-focused activities, create job aids, and eliminate unnecessary training.

zoonk-design

16
from diegosouzapw/awesome-omni-skill

Design philosophy and UI/UX guidelines inspired by Apple, Linear, and Vercel. Use when planning new features, designing interfaces, reviewing implementations, or making visual and interaction design decisions.

widget-design

16
from diegosouzapw/awesome-omni-skill

Best practices for designing UI widgets in xmcp. Use when creating interactive widgets for GPT Apps or MCP Apps, choosing between React components and template literals, designing widget layouts, handling state and data fetching, or troubleshooting widget rendering issues.

web-design-guidelines

16
from diegosouzapw/awesome-omni-skill

Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".

vibe-techdesign

16
from diegosouzapw/awesome-omni-skill

Create a Technical Design Document for your MVP. Use when the user wants to plan architecture, choose tech stack, or says "plan technical design", "choose tech stack", or "how should I build this".

ui-ux-designer

16
from diegosouzapw/awesome-omni-skill

Create interface designs, wireframes, and design systems. Masters user research, accessibility standards, and modern design tools.

ui-ux-design-system

16
from diegosouzapw/awesome-omni-skill

Expert in building premium, accessible UI/UX design systems for SaaS apps. Covers design tokens, component architecture with shadcn/ui and Radix, dark mode, glassmorphism, micro-animations, responsive layouts, and accessibility. Use when: ui, ux, design system, shadcn, radix, tailwind, dark mode, animation, accessibility, components, figma to code.

ui-designer

16
from diegosouzapw/awesome-omni-skill

Generate and serve live HTML/CSS/JS UI designs from natural language prompts. Use when the user asks to design, create, build, or prototype a website, landing page, UI, dashboard, web page, or frontend mockup. Also triggers on requests to update, tweak, or iterate on a previously generated design. Replaces traditional UI design + frontend dev workflow.

ui-design

16
from diegosouzapw/awesome-omni-skill

Applies consistent renderer UI/UX implementation patterns using a Vercel-inspired white theme, strong accessibility defaults, and repository component conventions.

ui-design-styles

16
from diegosouzapw/awesome-omni-skill

Comprehensive guidance for applying modern UI design styles, including Soft UI, Dark Mode, Flat Design, Neumorphism, Glassmorphism, and Aurora UI Gradients. Use when a user asks to: (1) Apply a specific UI style to a project, (2) Create a modern, visually appealing UI prototype, (3) Improve accessibility while following design trends, or (4) Understand the technical implementation of specific UI effects like frosted glass or soft shadows.