更新时间:2023-11-22 23:19:58
也许您期望某种可以使类型特征起作用的魔术。在这种情况下,请失望-没有魔法。类型特征是为每种类型手动定义的。例如,考虑 iterator_traits
,它为迭代器提供typedef(例如 value_type
)。
Perhaps you’re expecting some kind of magic that makes type traits work. In that case, be disappointed – there is no magic. Type traits are manually defined for each type. For example, consider iterator_traits
, which provides typedefs (e.g. value_type
) for iterators.
使用它们,您可以编写
iterator_traits<vector<int>::iterator>::value_type x;
iterator_traits<int*>::value_type y;
// `x` and `y` have type int.
但是要使这项工作有效,实际上其中有一个显式定义 < iterator>
标头,其内容如下:
But to make this work, there is actually an explicit definition somewhere in the <iterator>
header, which reads something like this:
template <typename T>
struct iterator_traits<T*> {
typedef T value_type;
// …
};
这是 iterator_traits的部分专业化
类型用于类型为 T * $ c>的类型,即某种通用类型的指针。
This is a partial specialization of the iterator_traits
type for types of the form T*
, i.e. pointers of some generic type.
同样, iterator_traits
专用于其他迭代器,例如 typename vector< T> :: iterator
。
In the same vein, iterator_traits
are specialized for other iterators, e.g. typename vector<T>::iterator
.