std::is_floating_point 是标准库中定义在 头文件里的类型特征模板,用于编译期判断类型是否为浮点类型(如 float、double、long double 等),返回 std::integral_constant,支持 if constexpr、SFINAE 和 requires 约束。
std::is_floating_point 是什么类型特征
std::is_floating_point 是标准库中定义在 头文件里的一个变量模板(C++17 起)或类模板(C++11/14),用于在编译期判断某个类型是否为浮点类型(即 float、double、long double,以及可能的扩展浮点类型如 __float128,取决于实现)。
它不关心值,只看类型本身;返回的是一个 std::integral_constant,所以能直接用在 if constexpr、SFINAE 或 requires 约束里。
怎么在 if constexpr 中做分支选择
C++17 起最常用、最直观的用法就是在模板函数里配合 if constexpr 做编译期分发,避免为非浮点类型实例化不合法代码(比如调用 std::sin)。
- 必须包含
- 使用
std::is_floating_point_v(C++17 变量模板别名)比写std::is_floating_point::value更简洁 - 分支内不能出现对非浮点类型非法的操作,否则即使不执行也会编译失败
template
auto safe_sin(T x) {
if constexpr (std::is_floating_point_v) {
return std::sin(x); // 仅当 T 是浮点时才参与编译
} else {
return x; // 其他类型直接返回原值
}
}
怎么用在 SFINAE 或 requires 约束里
在需要显式约束模板参数的场景下(比如重载函数、概念约束),std::is_floating_point 可以作为 SFINAE 条件或 requires 子句的一部分。