static_assert with an example in C++
static_assert is a compile-time assertion introduced in C++11. It checks a condition during compilation and produces an error if the condition is false, helping catch logic bugs early.
๐น Syntax
static_assert(condition, "error message");
condition: a constant expression (evaluated at compile-time)"error message": shown if the assertion fails
๐ธ Example: Assert Size of Type
static_assert(sizeof(int) == 4, "int must be 4 bytes");
If int is not 4 bytes, you’ll get a compile-time error like:
error: static assertion failed: int must be 4 bytes
๐น Example: Template Check
template<typename T>
void process(T value) {
static_assert(std::is_integral<T>::value, "Only integral types allowed");
// ... implementation ...
}
process(42); // โ
OK
process(3.14); // โ Compile-time error: Only integral types allowed
C++17 Enhancement: Single-argument static_assert
In C++17, the message became optional:
static_assert(sizeof(void*) == 8); // No message needed