traits类如何工作? [英] how do traits classes work?
问题描述
我正在阅读Scott Meyers的 有效的C ++ 。他正在谈论traits类,我知道我需要他们在编译期间确定对象的类型,但我不能理解他的解释这些类实际上做什么? (从技术的角度)
I'm reading Scott Meyers' Effective C++. He is talking about traits classes, I understood that I need them to determine the type of the object during compilation time, but I can't understand his explanation about what these classes actually do? (from technical point of view)
推荐答案
也许你期待一种魔法,使类型特征工作。在这种情况下,失望 - 没有魔法。类型特征是为每种类型手动定义的 。例如,考虑 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 *
,即一些通用类型的指针。
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向量< T> :: iterator
。
In the same vein, iterator_traits
are specialized for other iterators, e.g. typename vector<T>::iterator
.
这篇关于traits类如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!