进行编译时断言检查。
语法
static_assert ( 布尔常量表达式 , 消息 ) | (C++11 起) | |
static_assert ( 布尔常量表达式 ) | (C++17 起) | |
解释
布尔常量表达式 | - | 按语境转换成 bool 类型的常量表达式 |
消息 | - | 当 布尔常量表达式 为 false 时将出现的可选的 (C++17 起)字符串字面量 |
static_assert 声明可以出现在命名空间和块作用域中(作为块声明),也可以在类体中(作为成员声明)。
若 布尔常量表达式 返回 true,则此声明无效果。否则发布编译时错误,而若存在 消息,则诊断消息中包含其文本。
消息 可省略。 | (C++17 起) |
注解
因为 消息 必须是字符串字面量,所以它不能容纳动态信息,乃至自身并非字符串字面量的常量表达式。特别是它不能容纳模板类型实参的名字。
示例
运行此代码
- #include <type_traits>
- template <class T>
- void swap(T& a, T& b)
- {
- static_assert(std::is_copy_constructible<T>::value,
- "Swap requires copying");
- static_assert(std::is_nothrow_copy_constructible<T>::value
- && std::is_nothrow_copy_assignable<T>::value,
- "Swap requires nothrow copy/assign");
- auto c = b;
- b = a;
- a = c;
- }
- template <class T>
- struct data_structure
- {
- static_assert(std::is_default_constructible<T>::value,
- "Data Structure requires default-constructible elements");
- };
- struct no_copy
- {
- no_copy ( const no_copy& ) = delete;
- no_copy () = default;
- };
- struct no_default
- {
- no_default () = delete;
- };
- int main()
- {
- int a, b;
- swap(a, b);
- no_copy nc_a, nc_b;
- swap(nc_a, nc_b); // 1
- data_structure<int> ds_ok;
- data_structure<no_default> ds_error; // 2
- }
可能的输出:
- 1: error: static assertion failed: Swap requires copying
- 2: error: static assertion failed: Data Structure requires default-constructible elements
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
DR | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
CWG 2039 | C++11 | 只要求转换前的表达式是常量 | 转换本身必须也在常量表达式中合法 |
当前内容版权归 cppreference 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cppreference .