Master compile-time programming with constexpr, type traits, and variadic templates.
Harness the power of C++ compile-time computation.
constexpr - a powerful C++11/14/17 feature that enables compile-time computation, improving performance and enabling use in template arguments.constexpr int square(int n) {
return n * n;
}
// Computed at compile time!
constexpr int result = square(5); // 25constexpr int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
constexpr int fact5 = factorial(5); // 120constexpr double PI = 3.14159265358979;
constexpr double circle_area(double r) {
return PI * r * r;
}constexpr int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
// Use in array size
int arr[fibonacci(10)]; // Size 55Square of 5: 25
Factorial of 6: 720
Circle area (r=3): 28.2743
Fibonacci(10): 55
All computed at compile time!
constexpr int func(int x) { return x; }constexpr int val = func(5);Review feedback below
<type_traits> to query and manipulate types at compile time. Essential for template metaprogramming.#include <type_traits>cout << is_integral::value << endl; // 1 (true)
cout << is_floating_point::value; // 1 (true)
cout << is_pointer::value << endl; // 1 (true)
cout << is_class::value << endl; // 1 (true) template
void process(T value) {
static_assert(is_integral::value,
"T must be an integral type");
// ... process integer
} // Remove const/reference
remove_const::type x; // int
remove_reference::type y; // int
// Add const/pointer
add_const::type z; // const int
add_pointer::type p; // int* // Choose type based on condition
conditional::type a; // int
conditional::type b; // double int is integral: true
double is floating: true
int* is pointer: true
string is class: true
Types validated at compile time!
is_integral<T>::valuestatic_assert(condition, "msg")remove_const<T>::typeis_integral_v<T> shorthandReview feedback below
std::tuple, std::make_unique, and more.// typename... is parameter pack
template
void func(Args... args) {
// args... is pack expansion
} template
void count_args(Args... args) {
cout << "Count: " << sizeof...(Args) << endl;
}
count_args(1, 2, 3, 4); // Count: 4 // Base case
void print() {
cout << endl;
}
// Recursive case
template
void print(T first, Rest... rest) {
cout << first << " ";
print(rest...); // Recurse with remaining
} template
auto sum(Args... args) {
return (args + ...); // Fold over +
}
cout << sum(1, 2, 3, 4); // 10 Argument count: 4
Printing: 1 2 3 hello
Sum: 15
Product: 120
template<typename... Args>sizeof...(Args)func(args...)(args + ...) or (... + args)Review feedback below