static_assert是从c++11开始提供的支持,执行编译时断言检查;
语法:
static_assert(bool-constexpr, message) //(since C++11)
static_assert(bool-constexpr) //(since C++17)
参数说明:
bool-constexpr:bool类型的常量表达式;
message: 可选参数(since C++17)bool-constexpr为false时的提示字符串;
使用static_assert,我们可以在编译期间发现更多的错误,用编译器来强制保证一些契约,并帮助我们改善编译信息的可读性,尤其是用于模板的时候。
static_assert可以用在全局作用域中,命名空间中,类作用域中,函数作用域中,几乎可以不受限制的使用。编译器在遇到一个static_assert语句时,通常立刻将其第一个参数作为常量表达式进行演算,但如果该常量表达式依赖于某些模板参数,则延迟到模板实例化时再进行演算,这就让检查模板参数成为了可能。
由于是static_assert编译期间断言,不生成目标代码,因此static_assert不会造成任何运行期性能损失。
示例:
#include <iostream>
#include <type_traits>
struct A { };
struct B { B(B&&){} };
struct C { C(C&&) noexcept {} };
void test() {
static_assert(std::is_nothrow_move_constructible<A>::value,
"class A requires noexcept move-constructible type");
static_assert(std::is_nothrow_move_constructible<B>::value,
"class B requires noexcept move-constructible type");
static_assert(std::is_nothrow_move_constructible<C>::value,
"class C requires noexcept move-constructible type");
}
int main() {
test();
return 0;
}
编译报错:
In function 'void test()':
11:5: error: static assertion failed: class B requires noexcept move-constructible type