首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Static Assertion

执行编译时断言检查。

句法

static_assert ( bool_constexpr , message )

?

(since C++11)

static_assert ( bool_constexpr )

?

(since C++17)

解释

bool_constexpr

-

a contextually converted constant expression of type bool

message

-

optional (since C++17)string literal that will appear as compiler error if bool_constexpr is false

静态断言声明可能会出现在命名空间中,并阻塞作用域%28作为块声明%29和类体内%28作为a成员声明29%。

中频bool[医]警员回报true这个声明没有任何效果。否则,将发出编译时错误,并且诊断消息中包含消息文本(如果有的话)。

message can be omitted.

(since C++17)

由于消息必须是字符串文字,所以它不能包含动态信息,甚至不能包含常数表达式这不是字符串文本本身。特别是,它不能包含名称在...模板类型参数...

缺陷报告

以下行为更改缺陷报告追溯应用于先前发布的C++标准。

DR

Applied to

Behavior as published

Correct behavior

CWG 2039

C++11

only the expression before conversion is required to be constant

the conversion must also be valid in a constant expression

二次

代码语言:javascript
复制
#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_move_constructible<T>::value
               && std::is_nothrow_move_assignable<T>::value,
                  "Swap may throw");
    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
}

二次

可能的产出:

二次

代码语言:javascript
复制
1: error: static assertion failed: Swap requires copying
2: error: static assertion failed: Data Structure requires default-constructible elements

二次

另见

  • #误差
  • 断言
  • 类型性状

C静态文档[医]断言

*。

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com