Use of traits is another common programming technique in conjunction with template programming. A traits class is a shadow class that accompanies another type and contains information that is associated with the other type.
The standard C++ library has several examples of traits: the character traits are an example. As you might know the standard string class is a class templates that is parameterized on the character type in order to allow for representation of tiny character and wide character string, at least. In principle, the string class template, which is actually named basic_string, can be instantiated on any character type, not just the two character type that are predefined by the C++ language. If for instance someone needs to represent, say Japanese, characters as a structure named Jchar, then the basic_string template can be used to create a string class for Japanese characters, namely basic_string<Jchar>.
Imagine you are implementing such a string class template? You would find that there is information that you would need, but that is not contained in the character type. For instance, how would you calculate the string length? By counting all characters in the string until you find the end-of-string character. How would you know which is the end-of-string character? Okay, we know it is '\0' in the case of tiny characters of type char, and there is a corresponding end-of-string character defined for characters of type wchar_t, but how would you identify the end-of-string character for Japanese characters of type Jchar? Quite obviously the information about the end-of-string character is a piece of information that is associated with each character type, but is not contained in the character type. And this is exactly what traits are for: they provide information that is associated with a type, but is not contained in the type.
A traits type is a shadow type, typically a class
template that can
be instantiated or specialized for a group of types and provides
information
associated with each type. The character traits for instance,
see
the char_traits class template in the standard C++ library, contains a
static character constant that designates the end-of-string character
for
the character type it is instantiated for.
本文围绕C++标准库展开,介绍了Traits的概念。以标准字符串类模板basic_string为例,说明其可基于任意字符类型实例化。在实现字符串类模板时,会遇到字符类型中未包含的信息,如字符串结束字符,而Traits正是用于提供与类型相关但不在类型内的信息。
768

被折叠的 条评论
为什么被折叠?



