Back to results for “Templates”
C++ › Constexpr & Compile-Time

What is compile-time computation good for, and what are its trade-offs?

Advanced

Answer

Moving work to compile time (via constexpr/consteval, templates) removes runtime cost, enables constants for array sizes and template arguments, and can catch errors earlier. Trade-offs include longer compile times, increased code/complexity, and debugging difficulty of compile-time logic. It's most valuable for hot constants, lookup tables, and configuration known at build time.
constexpr auto table = makeSineTable();  // built at compile time
Real-world example Precomputing a CRC or sine table at compile time eliminates its runtime initialization cost.

Common follow-ups: What are the costs of heavy compile-time computation? | When is it worthwhile?