static_assert 声明 (C++11)

可以声明静态断言以在编译时检测和诊断常见使用错误。 static_assert 声明采用以下格式:

static_assert 声明语法

读取语法图跳过可视语法图 static_assert ( constant_expression , 字符串型文字 ) ;

constant_expression 必须是可以上下文转换为 bool的常量表达式。 如果以这种方式转换的表达式的值为 false ,那么编译器将发出严重错误,其中包含带有 static_assert 声明的源位置的 string literal 。 否则, static_assert 声明无效。

您可以在使用 using 声明的任何位置声明静态断言,包括名称空间作用域,块作用域和类成员声明列表。

静态断言的声明不声明新的类型或对象,也不暗示运行时的任何大小或时间成本。

C++ 编程语言还支持所有语言级别的 _Static_assert 关键字,以提高与 C 编程语言的兼容性。

将静态断言添加到 C++ 语言具有以下优点:
  • 库可以在编译时检测一般用法错误。
  • C++ 标准库的实现可以检测和诊断常见使用错误,从而提高可用性。
可以声明静态断言以在编译时检查重要的程序不变量。

示例 :static_assert 声明

以下示例说明在名称空间作用域中使用 static_assert 声明。
static_assert(sizeof(long) >= 8, "64-bit code generation not 
enabled/supported.");
以下示例演示了在类作用域中使用具有模板的 static_assert 声明。
#include <type_traits>
#include <string>

template<typename T>
struct X {
   static_assert(std::tr1::is_pod<T>::value, "POD required to 
instantiate class template X.");
   // ...
};

int main() {
   X<std::string> x;
}

以下示例演示了如何将块作用域中的 static_assert 声明与模板配合使用:

template <typename T, int N>
void f() {
   static_assert (N >=0, "length of array a is negative.");
   T a[N];
   // ...
}

int main() {
   f<int, -1>();
}
以下示例显示了如何使用具有无效常量表达式的 static_assert 声明。
 static_assert(1 / 0, "never shows up!");
编译此程序时,编译器不会在 static_assert 声明中显示 string literal 。 相反,编译器会发出一条错误消息,指示除数不能为零。