static_assert
是 C++11 引入的一个关键字,用于在编译时进行断言检查
- 未定义的常量:
#include#include int main() { static_assert(true, "This should not cause a compilation error"); static_assert(false, "This will cause a compilation error"); // Error: constant expression required }
- 类型不匹配:
#include#include template void foo(T t) { static_assert(std::is_same ::value, "T must be an integer"); } int main() { foo(42); // OK foo(3.14); // Error: static assertion failed: T must be an integer }
- 表达式计算失败:
#includeint main() { int a = 10; int b = 0; static_assert(a / b == 5, "Division by zero should not occur"); // Error: static assertion failed: a / b == 5 }
- 自定义类型特性检查失败:
#include#include struct MyStruct { int x; }; template void foo(T t) { static_assert(std::is_integral ::value, "T must be an integral type"); } int main() { foo(MyStruct{42}); // OK foo(3.14); // Error: static assertion failed: T must be an integral type }
这些示例展示了 static_assert
在不同情况下的常见错误。注意,当 static_assert
失败时,编译器会生成一个编译错误,并显示提供的错误消息。