Content area
Full Text
Maximizing the amount of generic code
Generic programming-that is, writing code that works with any data type meeting a set of requirements-has become the method of choice for delivering reusable code. However, there are times in generic programming when generic just isn't good enough-sometimes the differences between types are too great for an efficient generic implementation. This is when the traits technique becomes important. By encapsulating those properties that need to be considered on a type-by-type basis inside a traits class, you can minimize the amount of code that has to differ from one type to another, and maximize the amount of generic code.
For example, when working with character strings, one common operation is to determine the length of a null-terminated string. Clearly, it's possible to write generic code that can do this, but it turns out that there are much more efficient methods available. The C library functions stren and wcslen, for instance, are usually written in assembler, and with suitable hardware support can be considerably faster than a generic version written in C++. The authors of the C++ Standard Library realized this, and abstracted the properties of char and wchar_t into the class char_ traits. Generic code that works with character strings can simply use char traits<>::length to determine the length of a null-terminated string, safe in the knowledge that specializations of char_traits will use the most appropriate method available to them.
Type Traits
Class char traits is a classic example of a collection of type-specific properties wrapped up in a single class-what Nathan Myers terms a "baggage class" (see "Traits," by Nathan Myers, C++ Report, June 1995). In the Boost type-traits library (http://www.boost.org/, we have written a set of very specific traits classes, each of which encapsulate a single trait from the C++ type system. For example, is a type a pointer or a reference type, or does a type have a trivial constructor, or a const qualifier? The type-traits classes share a unified design. Each class has a single member called value- a compile-time constant that is true if the type has the specified property, and false otherwise. These classes can be used in generic programming to determine the properties of a given type and introduce optimizations that...