Template metaprogramming — compile-time computation using templates.
1// Compile-time factorial2template<int N>3struct Factorial {4 static const int value = N * Factorial<N - 1>::value;5};67// Base case8template<>9struct Factorial<0> {10 static const int value = 1;11};1213int main() {14 std::cout << Factorial<5>::value; // 120 (computed at compile-time)15}
constexpr (C++11, improved in C++14/17/20):
1constexpr int factorial(int n) {2 return n <= 1 ? 1 : n * factorial(n - 1);3}45int arr[factorial(5)]; // arr[120]
Type traits:
1#include <type_traits>23// Check if type is pointer4static_assert(std::is_pointer_v<int*>);56// Remove reference7using T = std::remove_reference_t<int&>; // int
Enable_if (SFINAE):
1template<typename T>2std::enable_if_t<std::is_integral_v<T>>3func(T value) {4 // Only for integral types5}
Modern C++20 (concepts):
1template<std::integral T>2void func(T value) {3 // Only for integral types4}