c++ static_assert

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值