静态断言(static_assert)

静态断言(static_assert)

static_assertC++11 提供的编译期断言工具。它和运行时的 assert 最大区别在于:如果条件不满足,程序根本编不过。

1. 基本语法

1
static_assert(condition, "message");

如果 condition 为假,编译器会直接报错,并带上你写的提示信息。

2. 一个最简单的例子

1
static_assert(sizeof(int) == 4, "int size must be 4");

这类写法经常用于平台相关检查。

3. 和 assert 的区别

assert

  • 运行时检查
  • 程序先能编译通过

static_assert

  • 编译期检查
  • 条件不满足时直接停止编译

所以 static_assert 更适合检查那些在编译阶段就应该成立的前提。

4. 常见使用场景

4.1 类型大小检查

1
static_assert(sizeof(long long) >= 8, "need 64-bit integer");

4.2 模板参数限制

1
2
3
4
5
template <typename T>
void func()
{
static_assert(std::is_integral<T>::value, "T must be integral");
}

4.3 平台和配置检查

有些库会在编译期确认某些编译选项、结构大小、对齐方式等。

5. 一个模板示例

1
2
3
4
5
6
7
#include <type_traits>

template <typename T>
struct MyData
{
static_assert(std::is_pod<T>::value, "T must be POD type");
};

这样一来,错误会在实例化阶段尽早暴露出来。

总结

static_assert 的价值就在于“尽早失败”。
凡是那些在编译期就能判断对错的条件,都很适合用它检查。特别是在模板代码和底层库代码里,它比运行时断言更有效,也更省排查成本。