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
失敗時,編譯器會生成一個編譯錯誤,并顯示提供的錯誤消息。