进行编译时断言检查。

语法

static_assert ( 布尔常量表达式 , 消息 ) (C++11 起)
static_assert ( 布尔常量表达式 ) (C++17 起)

解释

布尔常量表达式 - 按语境转换成 bool 类型的常量表达式
消息 - 当 布尔常量表达式 为 false 时将出现的可选的 (C++17 起)字符串字面量

static_assert 声明可以出现在命名空间和块作用域中(作为块声明),也可以在类体中(作为成员声明)。

若 布尔常量表达式 返回 true,则此声明无效果。否则发布编译时错误,而若存在 消息,则诊断消息中包含其文本。


消息 可省略。
(C++17 起)

注解

因为 消息 必须是字符串字面量,所以它不能容纳动态信息,乃至自身并非字符串字面量的常量表达式。特别是它不能容纳模板类型实参名字

示例

运行此代码

  1. #include <type_traits>
  2.  
  3. template <class T>
  4. void swap(T& a, T& b)
  5. {
  6. static_assert(std::is_copy_constructible<T>::value,
  7. "Swap requires copying");
  8. static_assert(std::is_nothrow_copy_constructible<T>::value
  9. && std::is_nothrow_copy_assignable<T>::value,
  10. "Swap requires nothrow copy/assign");
  11. auto c = b;
  12. b = a;
  13. a = c;
  14. }
  15.  
  16. template <class T>
  17. struct data_structure
  18. {
  19. static_assert(std::is_default_constructible<T>::value,
  20. "Data Structure requires default-constructible elements");
  21. };
  22.  
  23. struct no_copy
  24. {
  25. no_copy ( const no_copy& ) = delete;
  26. no_copy () = default;
  27. };
  28.  
  29. struct no_default
  30. {
  31. no_default () = delete;
  32. };
  33.  
  34. int main()
  35. {
  36. int a, b;
  37. swap(a, b);
  38.  
  39. no_copy nc_a, nc_b;
  40. swap(nc_a, nc_b); // 1
  41.  
  42. data_structure<int> ds_ok;
  43. data_structure<no_default> ds_error; // 2
  44. }

可能的输出:

  1. 1: error: static assertion failed: Swap requires copying
  2. 2: error: static assertion failed: Data Structure requires default-constructible elements

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

DR 应用于 出版时的行为 正确行为
CWG 2039 C++11 只要求转换前的表达式是常量 转换本身必须也在常量表达式中合法