zoukankan      html  css  js  c++  java
  • c++11 static_assert

    c++中想要在编译时期进行断言,在之前的标准中可以采用1/0来判断,如下:

     1 #include <cstring>
     2 using namespace std;
     3 
     4 #define assert_static(e) do{ enum{ assert_static__ = 1 / (e) }; } while(0)
     5 
     6 template<typename T, typename U>
     7 int bit_copy(T& a, U& b) {
     8  assert_static(sizeof(a) == sizeof(b));
     9  memcpy(&a, &b, sizeof(b));          
    10 }
    11 
    12 int main() {
    13  int a = 0x2468;
    14  double b;
    15  bit_copy(a, b);   
    16 }

    在c++11中,可以使用static_assert断言,且可以打印出具体的出错信息。static_assert接收两个参数,一个是断言表达式,此表达式需要返回一个bool值;另一个则是警告信息,通常是字符串。以上代码可以修改如下:

     template<typename T, typename U>
      int bit_copy(T& a, U& b) {
       static_assert(sizeof(a) == sizeof(b), "the parameters of bit_copy must have same width");
       memcpy(&a, &b, sizeof(b));          
     }

    编译会得到如下信息:

    error:static assertion failed: "the parameters of bit_copy must have same width."
  • 相关阅读:
    数组中重复的数字
    第一个只出现一次的字符位置
    丑数
    字符串的排列
    把数组排成最小的数
    圆圈中最后剩下的数
    同步通信与异步通信
    S3C2440 UART串口驱动
    ARM处理器工作模式
    s3c2440系统时钟
  • 原文地址:https://www.cnblogs.com/sssblog/p/10178415.html
Copyright © 2011-2022 走看看