C++ static_assert

18 阅读1分钟

static_assert是C++的编译期断言指令,属于C++的关键字。

static_assert的用法:

// 
static_assert(编译期常量表达式);
static_assert(编译期常量表达式, “字符串(用于表征断言有误)”);

static_assert 的时候需要包含库文件<type_traits>,不是这个库文件里定义了这个名为静态断言的函数。而是由于静态断言这个C++关键字用到了在库文件中提供的std::is_same_vstd::is_same_v是编译器模板变量,本质是编译期内可以完成例化的常量。

// 标准库内部实现(简化版)
template <typename T, typename U>
inline constexpr bool std::is_same_v = std::is_same<T, U>::value;