C++ 的 静态断言
等级 5565 次按键
static_assert 在编译期检查条件,若为 false 则以给定消息终止编译。这里检查模板参数 T 的要求以及关于 int 的假设;两个实例化都通过,因此程序正常运行。
C++ 代码
1template<typename T>2class SafeContainer { // 模板实例化时针对每个 T 进行检查3 static_assert(is_default_constructible_v<T>, "T must be default constructible"); // 把 T 的大小限制在 64 字节以内4 static_assert(sizeof(T) <= 64, "T is too large for this container");5 T data;6public: // = default 使用编译器生成的构造函数7 SafeContainer() = default; // 保存值的副本8 SafeContainer(const T& v) : data(v) {}9 T get() const { return data; }10};11 // 条件不成立时会以此消息终止编译12static_assert(sizeof(int) == 4, "int must be 4 bytes");13static_assert(is_integral_v<int>, "int must be integral");14 // int 通过模板的两项检查15SafeContainer<int> ci(42);// string 也能通过(其大小通常为 24 或 32 字节)16SafeContainer<string> cs("hello");17 // 输出“Int: 42”18cout << "Int: " << ci.get() << endl;// 输出“String: hello”19cout << "String: " << cs.get() << endl;运行结果
Int: 42 String: hello
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 C++ 代码中需要输入的符号及其出现次数。
<× 18"× 14(× 14)× 14;× 12_× 9>× 5,× 4:× 4=× 4