⚙️ C++ Advanced

What is template metaprogramming in C++?

Answer

Template Metaprogramming (TMP) is a programming technique where templates perform computations at compile time — moving work from runtime to compile time for zero-overhead abstractions. Compile-time factorial (classic TMP): template<int N> struct Factorial { static constexpr int value = N * Factorial<N-1>::value; }; template<> // Base case specialization struct Factorial<0> { static constexpr int value = 1; }; static_assert(Factorial<5>::value == 120); // Computed at compile time!. Modern approach — constexpr functions (C++11+): constexpr int factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); } constexpr int f5 = factorial(5); // 120 -- compile time. Easier to read and debug than TMP structs. Type-level programming: // Type list: template<typename...> struct TypeList {}; // Get head: template<typename T, typename... Rest> struct Head<TypeList<T, Rest...>> { using type = T; }; // Conditional type selection: template<bool Cond, typename Then, typename Else> struct Conditional { using type = Then; }; template<typename Then, typename Else> struct Conditional<false, Then, Else> { using type = Else; }; using MyType = Conditional<sizeof(int)==4, int32_t, int64_t>::type;. std::tuple internals: recursive variadic template: template<typename T, typename... Rest> class tuple : tuple<Rest...> { T value; };. if constexpr (C++17): replaces SFINAE for compile-time branching: template<typename T> void process(T value) { if constexpr (std::is_integral_v<T>) { // Only compiled for integral types } else { // Only compiled for non-integral types } }. TMP powers the STL, Boost.MPL, and many high-performance libraries.