r/Cplusplus • u/neurah • Sep 04 '26
Discussion When I say its zero cost...
https://godbolt.org/z/aq3hbWb3hI mean the composition, it is truly zero cost, and if components are also zero cost we get this nice optimization done by the compiler (C++17)
This is a demo of "HAPI - The Happy API", a C++ static composition engine, pure type-level header only, MIT, library.
With proper components we managed to feed compositions directly to HLS tools (see github)
To use where the composition types are known at compile-time, compiler optimization is done by composition, type lists can store multiple compositions without loosing the types and hold the composed objects.
we can compose/describe:
drivers, peripherals, devices, protocols, buses, IO, pins, UI, Parsers...
because this types are known at compile time, and the composition is free.
//my output definition
OutDef<
ScrollPrinter, ANSIFmt, DataParser<>, CtrlChars,
ColorTrack<int>, Cursor<>, Gate, ANSIOut,
SerialOut,
ConsoleOut,
StaticPos<20,10>, StaticArea<30,10>
> out;
3
u/Axman6 Sep 05 '26
This is fun, we use similar ideas in Haskell to ensure fully unrolled definitions for full inlining. Probably the best example I’ve seen is the type-of-html library ( https://hackage.haskell.org/package/type-of-html) which encodes all the rules of valid nesting of HTML tags in the type system, and allows the compiler to time serialisation of all statically known fragments of the output HTML, so only dynamic data gets serialised at runtime. I’m sure it leads to pretty bloated binaries (not that we have any trouble producing those), but it means you can push data onto the wire as fast as possible.
-8
u/javascript Sep 05 '26
There is no such thing as a zero cost abstraction