agentleFS
13eholder13eholder/Modern-Cpp-Skills/m04-zero-cost/SKILL.md

m04-zero-cost

Skill14 starsChanged 9 months agoMITView on GitHub

Mastering C++ Polymorphism: Templates, Concepts, and Virtual Functions. Triggers: templates, concepts, vtable, CRTP, static polymorphism, dynamic polymorphism, SFINAE.

7 other projects use a version of this.

Adopted by

Most recently taken up by

The file

Files
SKILL.md

C++ Zero-Cost Abstractions

Core Question

When do we determine the type?

  • Compile Time (Static): Templates, Concepts, CRTP. Zero runtime cost, larger binary.
  • Runtime (Dynamic): Virtual functions, std::any, std::variant. Flexible, vtable overhead.

Error → Design Question

IssueDesign Question
Template spewAre you missing Concepts constraints?
Linker errorDid you define template in .cpp instead of .h?
Object slicingDid you assign Derived to Base value?
Slow buildAre you overusing headers/templates?

Thinking Prompt

  1. Is the set of types known at compile time?
    • Yes? → Templates or std::variant.
    • No? → Inheritance (Virtual functions).
  2. Do I need to store them in a list?
    • Homogeneous? → std::vector<T>.
    • Heterogeneous? → std::vector<std::unique_ptr<Base>> or std::vector<std::variant<...>>.
  3. Does the interface match exactly?
    • Duck typing needed? → Templates (Concepts).
    • Strict hierarchy? → Inheritance.

Trace Up / Down

  • Trace Up:
    • Issue: "Virtual function call is too slow in tight loop."
    • Cause: Indirect branch misprediction.
    • Fix: Switch to Static Polymorphism (CRTP or Templates) if types are known.
  • Trace Down:
    • Intent: "I want a function that accepts anything that has .draw()."
    • Code (C++20): void render(Drawable auto& item) { item.draw(); }

Quick Reference

PatternDispatchCostUse When
virtualDynamicVtable + Cache missPlugins, Runtime extensions.
TemplateStaticCode bloatHigh perf, Type deduction.
std::functionDynamicAlloc + IndirectStoring callbacks.
std::variantStatic branchingBranch switchClosed set of types.
CRTPStaticZeroStatic inheritance.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.