static_assert 静态断言
不同于 assert 是在运行期对错误进行检查, static_assert 是在编译期对表达式进行判断,并打印出具体的出错信息。
语法格式:
static_assert(常量表达式,"提示字符串");
static_assert 接收两个参数,一个是常量表达式,该表达式返回 bool 类型,如果常量表达式的值为false,会在该行产生一条编译错误;第二个参数就是警告信息,通常是字符串。
实例:
#include <iostream>
#include <type_traits>
int main()
{
int b = 1;
static_assert(std::is_same_v<int&, decltype(b)>, "error");
return 0;
}
因为b的类型为 int ,上述代码会在编译时报错,在 vs2019 中会提示断言错误: