目录
static_assert声明
进行编译时语言检查
语法
static_assert(布尔常量表达式, 消息) | c++11起 |
static_assert(布尔常量表达式) | c++17起 |
解释
布尔常量表达式 - 按语境转换成bool类型的常量表达式
消息 - 当布尔常量表达式为false时,将出现的可选的字符串字面量
static_assert可出现在命名空间和作用域中(作为块声明), 也可以在类体中(作为成员声明)
若布尔常量表达式为true时,则此声明无效果,否则发布编译时错误,若存在消息, 则诊断消息中包含其文本
注解
因为消息必须是字符串字面量, 所以它不能容纳动态信息.乃至自身并非字符串字面量的常量表达式.特别是它不能容纳模板类型实参的名字
示例:
#include <iostream>
#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
}
运行结果
/home/program/workspace/cpp/static_assert/main.cpp:19:5: error: static assertion failed: Data Structure requires default-constructible elements
static_assert(std::is_default_constructible<T>::value,
^~~~~~~~~~~~~
/home/program/workspace/cpp/static_assert/main.cpp: In instantiation of ‘void swap(T&, T&) [with T = no_copy]’:
/home/program/workspace/cpp/static_assert/main.cpp:39:20: required from here
/home/program/workspace/cpp/static_assert/main.cpp:6:5: error: static assertion failed: Swap requires copying
static_assert(std::is_copy_constructible<T>::value,
^~~~~~~~~~~~~
/home/program/workspace/cpp/static_assert/main.cpp:8:5: error: static assertion failed: Swap requires nothrow copy/assign
static_assert(std::is_nothrow_copy_constructible<T>::value &&
^~~~~~~~~~~~~
/home/program/workspace/cpp/static_assert/main.cpp:11:10: error: use of deleted function ‘no_copy::no_copy(const no_copy&)’
auto c = b;
^