static_assert
是 C++11 引入的一个关键字,用于在编译时进行断言检查
#include <iostream>
#include <type_traits>
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 <iostream>
#include <type_traits>
template <typename T>
void foo(T t) {
static_assert(std::is_same<T, int>::value, "T must be an integer");
}
int main() {
foo(42); // OK
foo(3.14); // Error: static assertion failed: T must be an integer
}
#include <iostream>
int 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 <iostream>
#include <type_traits>
struct MyStruct {
int x;
};
template <typename T>
void foo(T t) {
static_assert(std::is_integral<T>::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
失败时,编译器会生成一个编译错误,并显示提供的错误消息。