首页 > 解决方案 > 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++typetraits

解决方案


原因只是历史原因。大多数类型特征首先在 C++11 中添加到库中。后来在 C++14 中添加了变量模板,而改变实现的那一点是不可行的,因为这太向后不兼容了。_v因此添加了带有后缀的变量,这成为了惯例。

以相同的方式添加新特征是因为在任何库中保持一致性很重要,更不用说标准库了。


推荐阅读