ev-spdlog-traits-conditional-static-cast-003¶
| 字段 | 值 |
|---|---|
| 项目 | gabime/spdlog |
| 固定 commit | 79524ddd08a4 |
| 路径 | include/spdlog/common.h |
| 行段 | L390-L399 |
| 特性 | 类型特征(type_traits) |
| 许可证 | MIT |
| 代码来源 | 项目源码 |
| 级别 | manual |
| 审核 | zyuhao7 @ 2026-11-03 |
| 测试代码 | 否 |
| 发现方式 | manual |
用法¶
用 enable_if 与 is_same 分成两个重载,避免同类型转换时的多余 cast
为什么典型¶
conditional_static_cast 在 T 与 U 相同时直接返回,不同时才 static_cast;两个互斥的 enable_if 重载让选择发生在编译期,没有运行期分支。
摘录¶
// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
template <typename T, typename U, enable_if_t<!std::is_same<T, U>::value, int> = 0>
constexpr T conditional_static_cast(U value) {
return static_cast<T>(value);
}
template <typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
constexpr T conditional_static_cast(U value) {
return value;
}
备注¶
生产头文件;两个重载的条件互为补集,任一组参数只会匹配其中一个,是类型特征驱动的重载选择。