Using static_assert with Non-constexpr Expressions
Can static_assert() be used with expressions that are not known at compile-time, such as values read from a file or user input?
No, static_assert() cannot be used with expressions that are not evaluatable at compile-time. The expression passed to static_assert() must be a constant expression, meaning it can be evaluated by the compiler during compilation.
For example, this is not allowed:
#include <cassert>
int main() {
int x;
std::cin >> x;
static_assert(x > 0, "x must be positive");
}error: static_assert expression is not an integral constant expressionFor runtime assertions based on user input or values read from files, use regular assert() or a custom runtime assertion macro instead:
#include <cassert>
#include <iostream>
int main() {
int x;
std::cin >> x;
assert(x > 0 && "x must be positive");
}Remember, assert() is typically stripped out in release builds, so you'd need to use a custom always-on assertion for checks you want enabled in release builds.
Some other notes on static_assert:
- The expression must be a boolean constant expression, not just any constant expression
static_assertis evaluated at compile-time, so it cannot depend on any runtime informationstatic_assertdoes not generate any runtime code or affect program performance- Use
static_assertto validate template parameters, sizes of types, and other invariants that can be checked at compile time
Errors and Assertions
Learn how we can ensure that our application is in a valid state using compile-time and run-time assertions.