作用
static_assert
是 C++11 引入的 编译时断言 机制,用于在编译阶段检查条件是否满足。如果条件不满足,编译器会报错并停止编译。
基本语法
static_assert(常量表达式, 错误消息字符串);
-
常量表达式:在编译时可求值的表达式(必须能转换为
bool
) -
错误消息:当断言失败时显示的编译错误信息
案例
using FirstType = std::tuple_element<0, MyTuple>::type;
static_assert(std::is_same_v<FirstType, int>, "First type should be int");
static_assert(std::is_integral_v<T>, "T must be integral");
constexpr int size = 10;
static_assert(size > 0, "Size must be