C++ 特征类是如何工作的,它们有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3979766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do traits classes work and what do they do?
提问by rookie
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)
我正在阅读 Scott Meyers 的Effective C++。他在谈论特征类,我知道我需要它们在编译时确定对象的类型,但我无法理解他对这些类实际上做什么的解释?(从技术角度)
采纳答案by Konrad Rudolph
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 manuallydefined for each type. For example, consider iterator_traits
, which provides typedefs (e.g. value_type
) for iterators.
也许您期待某种使类型特征起作用的魔法。在那种情况下,会感到失望——没有魔法。类型特征是为每种类型手动定义的。例如,考虑iterator_traits
,它value_type
为迭代器提供类型定义(例如)。
Using them, you can write
使用它们,你可以写
iterator_traits<vector<int>::iterator>::value_type x;
iterator_traits<int*>::value_type y;
// `x` and `y` have type int.
But to make this work, there is actually an explicit definitionsomewhere in the <iterator>
header, which reads something like this:
但是为了使这项工作,标题中的某处实际上有一个显式定义<iterator>
,其内容如下:
template <typename T>
struct iterator_traits<T*> {
typedef T value_type;
// …
};
This is a partial specializationof the iterator_traits
type for types of the form T*
, i.e. pointers of some generic type.
这是一个部分特的的iterator_traits
类型为类型形式的T*
,一些一般类型的,即指针。
In the same vein, iterator_traits
are specialized for other iterators, e.g. typename vector<T>::iterator
.
同样,iterator_traits
专门用于其他迭代器,例如typename vector<T>::iterator
.
回答by fredoverflow
Traits classes do notdetermine the type of the object. Instead, they provide additional information about a type, typically by defining typedefs or constants inside the trait.
Traits 类不决定对象的类型。相反,它们提供有关类型的附加信息,通常通过在特征内定义 typedef 或常量。