本站原创文章,转载请注明出处。
本站原创文章,转载请注明出处。
A trait is a type that conveys information used by another class or algorithm to determine policies at compile time. A traits class [Jos99] is a useful way to collect a set of traits that should be applied in a given situation to alter another class’s behavior appropriately. Traits and traits classes are C++ policy-based class design idioms [Ale01] that are widely used throughout the C++ standard library [Aus99].
For example, the char_traits class defines the traits of a character type, such as its data type and functions to compare, search for, and assign characters of that type. The C++ standard library provides specializations of char_traits<> for char and wchar_t. These character traits then modify the behavior of common classes, such as basic_iostream<> and basic_string<>. The iostream and string classes are defined by specializing the class templates with char_traits<char>. Similarly, the wiostream and wstring classes are defined by specializing the templates with char_traits<wchar_t>.
These C++ idioms are similar in spirit to the Strategy pattern [GoF], which allows substitution of class behavioral characteristics without requiring a change to the class itself. The Strategy pattern involves a defined interface that’s commonly bound dynamically at run time using virtual methods. In contrast, the traits and traits class idioms involve substitution of a set of class members and/or methods that can be bound statically at compile time using C++ parameterized types.
本站原创文章,转载请注明出处。