C++

Constexpr & Compile-Time

11 question(s)

What is template metaprogramming versus constexpr for compile-time work?

Advanced
Template metaprogramming performs compile-time computation via template instantiation and specialization (functional, verbose, historically the main tool). constexpr functions let you write compile-time logic in ordinary imperative C++, which is far more readable and maintainable. Modern C++ favors constexpr/consteval for values and reserves templates for type-level work, often combining both.
// constexpr is clearer than the equivalent recursive template
constexpr int factorial(int n){ return n<=1?1:n*factorial(n-1); }
Real-world example A team replaces cryptic recursive-template factorials with readable constexpr functions.

Common follow-ups: Why is constexpr more readable than TMP? | When are templates still needed?

Templates Constexpr & Compile-Time Constexpr & Compile-Time