Previous fileTop of DocumentContentsIndex pageNext file
Apache C++ Standard Library User's Guide

17.2 Using the Traits Technique

To implement a traits parameter for a class, you add it as an extra template parameter to your class. You then supply a class for this parameter that encapsulates all the specific operations. Usually that class is itself a template.

As an example, let's look at the matrix problem described in Section 17.1. When you want to add a new type to the matrix, you can use the traits technique and simply specialize the traits class, not the entire matrix. You do no more work than you have to, and you retain the ability to use the matrix on any reasonable number.

Here's how the matrix traits template and specializations for long and int might look. The example also includes a skeleton of the matrix class that uses the traits template.

Of course you don't even have to specialize on matrix_traits. You just have to make sure that you provide the interface that matrix expects from its traits template parameter.

Most of the time, the operations contained in a traits class are static functions so there's no need to actually instantiate a traits object.

The C++ Standard Library uses this technique to give the string class maximum flexibility and efficiency across a wide range of types. The char_traits traits class provides elementary operations on character arrays. In the simplest case, this means providing string a wstring with access to the C library functions for narrow and wide characters, for example strcpy and wcstrcpy.

See the char_traits entry in the Apache C++ Standard Library Reference Guide for a complete description of the traits class.



Previous fileTop of DocumentContentsIndex pageNext file