c++ - Why is type_traits implemented using structs
问题描述
Most of type traits are made using struct and template partial(or full) specialization. For example std::is_same
is implemented as
template<typename>
struct is_same : false_type {};
template<typename T>
struct is_same<T, T> : true_type {}; // partial specialization
The usage would be
bool are_equal = std::is_same<T, U>::value;
or
.. = std::is_same_v<T, U>;
which are both a bit ugly. At first I thought it was the only solution then I found out that variables can also be partially specialized(while functions can not). Type transformation traits cannot (obviusly) be variables but for "information" traits why this wouldn't be better than a struct?
template<typename>
inline constexpr bool is_same = false;
template<typename T>
inline constexpr bool is_same<T, T> = true;
And then
bool are_equal = std::is_same<T, U>;
解决方案
原因只是历史原因。大多数类型特征首先在 C++11 中添加到库中。后来在 C++14 中添加了变量模板,而改变实现的那一点是不可行的,因为这太向后不兼容了。_v
因此添加了带有后缀的变量,这成为了惯例。
以相同的方式添加新特征是因为在任何库中保持一致性很重要,更不用说标准库了。
推荐阅读
- vba - 使用 VBA(通过 python)在 ms-word 中对形状或内联形状进行分组
- r - 在 R 中自定义 lapply()
- java - 如何删除具有多对多关系的实体?JPA
- getstream-io - 如何在 GetStream 中获取上周活动
- office-js - 如何在 manifest.xml 中正确设置扩展权限节点?
- r - 带有shinyjs和flexdashboard的valueBox的模态弹出窗口
- css - 被错误考虑的媒体查询
- python - Pandas 和 Numpy 之间的 2D 索引分配差异
- php - 获取具有相似列值的多个 SQL 行
- ios - 订阅自定义 UIView 的变量