C++17中新增了static_assert,即静态断言,在编译期就能帮助程序员识别到代码中的一些断言错误, 并且可以在static_assert中加入第二个参数,将字符串直接作为编译结果输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <iostream>
using namespace std;
int main ( ) { MyClass<int, double> obj1; obj1.printSizeOfDataTypes( ); MyClass obj2( 1, 10.56 ); const int x = 5, y = 5; static_assert ( 1 == 0, "Assertion failed" ); static_assert ( 1 == 0 ); static_assert ( x == y );
return 0; }
|
1 2 3 4 5 6 7 8
| $ g++ test1.cc -std=c++17 test1.cc: In function ‘int main()’: test1.cc:28:27: error: static assertion failed: Assertion failed 28 | static_assert ( 1 == 0, "Assertion failed" ); | ~~^~~~ test1.cc:29:27: error: static assertion failed 29 | static_assert ( 1 == 0 ); |
|