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."

猜你喜欢

转载自www.cnblogs.com/sssblog/p/10178415.html